wide/session/oauth.go

163 lines
4.3 KiB
Go
Raw Normal View History

2019-05-17 06:28:50 +03:00
// Copyright (c) 2014-present, b3log.org
2019-05-16 18:17:25 +03:00
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package session
import (
2019-05-17 05:34:09 +03:00
"html/template"
2019-05-16 18:17:25 +03:00
"math/rand"
"net/http"
2019-05-16 19:41:52 +03:00
"os"
"path/filepath"
2019-05-16 18:17:25 +03:00
"strconv"
"strings"
"time"
2019-12-01 15:21:00 +03:00
"github.com/88250/gulu"
"github.com/88250/wide/conf"
"github.com/88250/wide/i18n"
2019-05-16 18:17:25 +03:00
)
var states = map[string]string{}
2019-12-13 15:50:35 +03:00
// LoginRedirectHandler redirects to HacPai auth page.
func LoginRedirectHandler(w http.ResponseWriter, r *http.Request) {
loginAuthURL := "https://hacpai.com/login?goto=" + conf.Wide.Server + "/login/callback"
2019-05-16 18:17:25 +03:00
2019-12-13 15:50:35 +03:00
state := gulu.Rand.String(16)
2019-05-16 18:17:25 +03:00
states[state] = state
2019-12-13 15:50:35 +03:00
path := loginAuthURL + "?state=" + state
2019-05-16 18:17:25 +03:00
http.Redirect(w, r, path, http.StatusSeeOther)
}
2019-12-13 15:50:35 +03:00
func LoginCallbackHandler(w http.ResponseWriter, r *http.Request) {
2019-05-16 18:17:25 +03:00
state := r.URL.Query().Get("state")
if _, exist := states[state]; !exist {
http.Error(w, "Get state param failed", http.StatusBadRequest)
return
}
delete(states, state)
2019-12-13 15:50:35 +03:00
userId := r.URL.Query().Get("userId")
userName := r.URL.Query().Get("userName")
avatar := r.URL.Query().Get("avatar")
2019-05-16 18:17:25 +03:00
2019-12-13 15:50:35 +03:00
user := conf.GetUser(userId)
2019-05-16 18:17:25 +03:00
if nil == user {
2019-12-13 15:50:35 +03:00
msg := addUser(userId, userName, avatar)
2019-05-16 18:17:25 +03:00
if userCreated != msg {
2019-05-24 16:04:25 +03:00
result := gulu.Ret.NewResult()
2019-05-24 16:52:17 +03:00
result.Code = -1
2019-05-16 18:17:25 +03:00
result.Msg = msg
2019-05-24 16:04:25 +03:00
gulu.Ret.RetResult(w, r, result)
2019-05-16 18:17:25 +03:00
return
}
}
// create a HTTP session
2019-05-16 19:41:52 +03:00
httpSession, _ := HTTPSession.Get(r, CookieName)
2019-12-13 15:50:35 +03:00
httpSession.Values["uid"] = userId
2019-05-16 18:17:25 +03:00
httpSession.Values["id"] = strconv.Itoa(rand.Int())
httpSession.Options.MaxAge = conf.Wide.HTTPSessionMaxAge
httpSession.Save(r, w)
2019-05-17 06:59:57 +03:00
http.Redirect(w, r, "/", http.StatusSeeOther)
2019-05-16 18:17:25 +03:00
}
2019-05-17 05:34:09 +03:00
// LoginHandler handles request of show login page.
func LoginHandler(w http.ResponseWriter, r *http.Request) {
model := map[string]interface{}{"conf": conf.Wide, "i18n": i18n.GetAll(conf.Wide.Locale),
"locale": conf.Wide.Locale, "ver": conf.WideVersion, "year": time.Now().Year()}
t, err := template.ParseFiles("views/login.html")
if nil != err {
logger.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
t.Execute(w, model)
}
2019-05-16 19:41:52 +03:00
// LogoutHandler handles request of user logout (exit).
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
2019-05-24 16:04:25 +03:00
result := gulu.Ret.NewResult()
defer gulu.Ret.RetResult(w, r, result)
2019-05-16 19:41:52 +03:00
httpSession, _ := HTTPSession.Get(r, CookieName)
httpSession.Options.MaxAge = -1
httpSession.Save(r, w)
}
// addUser add a user with the specified user id, username and avatar.
//
// 1. create the user's workspace
// 2. generate 'Hello, 世界' demo code in the workspace (a console version and a HTTP version)
// 3. update the user customized configurations, such as style.css
// 4. serve files of the user's workspace via HTTP
//
// Note: user [playground] is a reserved mock user
func addUser(userId, userName, userAvatar string) string {
if "playground" == userId {
return userExists
}
addUserMutex.Lock()
defer addUserMutex.Unlock()
for _, user := range conf.Users {
if strings.ToLower(user.Id) == strings.ToLower(userId) {
return userExists
}
}
2019-05-16 20:41:04 +03:00
workspace := filepath.Join(conf.Wide.Data, "workspaces", userId)
2019-05-16 19:41:52 +03:00
newUser := conf.NewUser(userId, userName, userAvatar, workspace)
conf.Users = append(conf.Users, newUser)
if !newUser.Save() {
return userCreateError
}
conf.CreateWorkspaceDir(workspace)
helloWorld(workspace)
conf.UpdateCustomizedConf(userId)
logger.Infof("Created a user [%s]", userId)
return userCreated
}
// helloWorld generates the 'Hello, 世界' source code.
func helloWorld(workspace string) {
dir := workspace + conf.PathSeparator + "src" + conf.PathSeparator + "hello"
if err := os.MkdirAll(dir, 0755); nil != err {
logger.Error(err)
return
}
fout, err := os.Create(dir + conf.PathSeparator + "main.go")
if nil != err {
logger.Error(err)
return
}
fout.WriteString(conf.HelloWorld)
fout.Close()
}