wide/session/users.go

327 lines
7.6 KiB
Go
Raw Normal View History

2014-11-12 18:13:14 +03:00
// Copyright (c) 2014, B3log
2014-11-17 06:20:35 +03:00
//
2014-11-12 18:13:14 +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
2014-11-17 06:20:35 +03:00
//
2014-11-12 18:13:14 +03:00
// http://www.apache.org/licenses/LICENSE-2.0
2014-11-17 06:20:35 +03:00
//
2014-11-12 18:13:14 +03:00
// 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.
2014-09-17 10:35:48 +04:00
package session
2014-08-31 14:50:38 +04:00
import (
"encoding/json"
"math/rand"
2014-09-12 13:10:58 +04:00
"net/http"
"os"
"path/filepath"
2014-11-17 05:49:25 +03:00
"runtime"
"strconv"
2014-11-20 06:17:43 +03:00
"sync"
2014-11-30 05:18:17 +03:00
"text/template"
2014-09-12 13:10:58 +04:00
2014-08-31 14:50:38 +04:00
"github.com/b3log/wide/conf"
"github.com/b3log/wide/i18n"
2014-09-01 16:50:51 +04:00
"github.com/b3log/wide/util"
2014-08-31 14:50:38 +04:00
"github.com/golang/glog"
)
const (
2014-12-08 09:02:39 +03:00
// TODO: i18n
2014-12-07 06:07:32 +03:00
userExists = "user exists"
2014-12-08 09:02:39 +03:00
emailExists = "email exists"
2014-12-07 06:07:32 +03:00
userCreated = "user created"
userCreateError = "user create error"
2014-08-31 14:50:38 +04:00
)
2014-11-20 06:17:43 +03:00
// Exclusive lock for adding user.
var addUserMutex sync.Mutex
2014-12-07 06:07:32 +03:00
// PreferenceHandler handles request of preference page.
2014-11-17 05:49:25 +03:00
func PreferenceHandler(w http.ResponseWriter, r *http.Request) {
httpSession, _ := HTTPSession.Get(r, "wide-session")
if httpSession.IsNew {
2014-12-11 10:32:24 +03:00
http.Redirect(w, r, conf.Wide.Context+"login", http.StatusFound)
2014-11-17 05:49:25 +03:00
return
}
httpSession.Options.MaxAge = conf.Wide.HTTPSessionMaxAge
httpSession.Save(r, w)
username := httpSession.Values["username"].(string)
user := conf.Wide.GetUser(username)
if "GET" == r.Method {
model := map[string]interface{}{"conf": conf.Wide, "i18n": i18n.GetAll(user.Locale), "user": user,
2014-11-26 06:24:24 +03:00
"ver": conf.WideVersion, "goos": runtime.GOOS, "goarch": runtime.GOARCH, "gover": runtime.Version(),
2014-11-30 05:18:17 +03:00
"locales": i18n.GetLocalesNames(), "gofmts": util.Go.GetGoFormats(),
"themes": conf.GetThemes(), "editorThemes": conf.GetEditorThemes()}
2014-11-17 06:20:35 +03:00
2014-11-17 05:49:25 +03:00
t, err := template.ParseFiles("views/preference.html")
if nil != err {
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
t.Execute(w, model)
2014-11-17 06:20:35 +03:00
2014-11-17 05:49:25 +03:00
return
}
2014-11-17 06:20:35 +03:00
2014-11-17 05:49:25 +03:00
// non-GET request as save request
2014-11-17 06:20:35 +03:00
succ := true
data := map[string]interface{}{"succ": &succ}
defer util.RetJSON(w, r, data)
args := struct {
FontFamily string
FontSize string
GoFmt string
Workspace string
Username string
Password string
2014-12-08 09:02:39 +03:00
Email string
2014-11-17 06:56:26 +03:00
Locale string
2014-11-30 05:18:17 +03:00
Theme string
EditorFontFamily string
EditorFontSize string
EditorLineHeight string
EditorTheme string
2014-12-01 09:49:16 +03:00
EditorTabSize string
2014-11-17 06:20:35 +03:00
}{}
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err)
succ = false
return
}
user.FontFamily = args.FontFamily
user.FontSize = args.FontSize
user.GoFormat = args.GoFmt
user.Workspace = args.Workspace
user.Password = args.Password
2014-12-08 09:02:39 +03:00
user.Email = args.Email
2014-11-17 06:56:26 +03:00
user.Locale = args.Locale
2014-11-30 05:18:17 +03:00
user.Theme = args.Theme
user.Editor.FontFamily = args.EditorFontFamily
user.Editor.FontSize = args.EditorFontSize
user.Editor.LineHeight = args.EditorLineHeight
user.Editor.Theme = args.EditorTheme
2014-12-01 09:49:16 +03:00
user.Editor.TabSize = args.EditorTabSize
2014-11-17 06:20:35 +03:00
2014-11-20 06:17:43 +03:00
conf.UpdateCustomizedConf(username)
2014-11-30 05:18:17 +03:00
2014-11-17 06:20:35 +03:00
succ = conf.Save()
2014-11-17 05:49:25 +03:00
}
// LoginHandler handles request of user login.
func LoginHandler(w http.ResponseWriter, r *http.Request) {
if "GET" == r.Method {
// show the login page
model := map[string]interface{}{"conf": conf.Wide, "i18n": i18n.GetAll(conf.Wide.Locale),
"locale": conf.Wide.Locale, "ver": conf.WideVersion}
t, err := template.ParseFiles("views/login.html")
if nil != err {
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
t.Execute(w, model)
return
}
// non-GET request as login request
2014-11-17 06:20:35 +03:00
succ := true
data := map[string]interface{}{"succ": &succ}
2014-09-01 16:50:51 +04:00
defer util.RetJSON(w, r, data)
args := struct {
Username string
Password string
}{}
2014-08-31 14:50:38 +04:00
2014-10-28 16:32:19 +03:00
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
2014-08-31 14:50:38 +04:00
glog.Error(err)
2014-11-17 06:20:35 +03:00
succ = false
2014-08-31 14:50:38 +04:00
return
}
2014-11-17 06:20:35 +03:00
succ = false
for _, user := range conf.Wide.Users {
if user.Name == args.Username && user.Password == args.Password {
succ = true
2014-11-17 06:20:35 +03:00
break
}
}
2014-08-31 14:50:38 +04:00
if !succ {
return
2014-08-31 14:50:38 +04:00
}
// create a HTTP session
httpSession, _ := HTTPSession.Get(r, "wide-session")
httpSession.Values["username"] = args.Username
httpSession.Values["id"] = strconv.Itoa(rand.Int())
httpSession.Options.MaxAge = conf.Wide.HTTPSessionMaxAge
httpSession.Save(r, w)
glog.Infof("Created a HTTP session [%s] for user [%s]", httpSession.Values["id"].(string), args.Username)
2014-08-31 14:50:38 +04:00
}
// LogoutHandler handles request of user logout (exit).
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
2014-09-01 16:50:51 +04:00
data := map[string]interface{}{"succ": true}
defer util.RetJSON(w, r, data)
httpSession, _ := HTTPSession.Get(r, "wide-session")
httpSession.Options.MaxAge = -1
httpSession.Save(r, w)
}
// SignUpUser handles request of registering user.
func SignUpUser(w http.ResponseWriter, r *http.Request) {
if "GET" == r.Method {
// show the user sign up page
firstUserWorkspace := conf.Wide.GetUserWorkspace(conf.Wide.Users[0].Name)
dir := filepath.Dir(firstUserWorkspace)
model := map[string]interface{}{"conf": conf.Wide, "i18n": i18n.GetAll(conf.Wide.Locale),
2014-10-30 13:21:44 +03:00
"locale": conf.Wide.Locale, "ver": conf.WideVersion, "dir": dir,
"pathSeparator": conf.PathSeparator}
t, err := template.ParseFiles("views/sign_up.html")
if nil != err {
glog.Error(err)
http.Error(w, err.Error(), 500)
return
}
t.Execute(w, model)
return
}
// non-GET request as add user request
succ := true
data := map[string]interface{}{"succ": &succ}
defer util.RetJSON(w, r, data)
var args map[string]interface{}
2014-08-31 14:50:38 +04:00
if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
glog.Error(err)
succ = false
2014-08-31 14:50:38 +04:00
return
}
2014-08-31 14:50:38 +04:00
username := args["username"].(string)
password := args["password"].(string)
2014-12-08 09:02:39 +03:00
email := args["email"].(string)
2014-12-08 09:02:39 +03:00
msg := addUser(username, password, email)
2014-12-07 06:07:32 +03:00
if userCreated != msg {
succ = false
data["msg"] = msg
}
2014-08-31 14:50:38 +04:00
}
2014-12-08 09:02:39 +03:00
// addUser add a user with the specified username, password and email.
//
// 1. create the user's workspace
// 2. generate 'Hello, 世界' demo code in the workspace
// 3. update the user customized configurations, such as style.css
// 4. serve files of the user's workspace via HTTP
2014-12-08 09:02:39 +03:00
func addUser(username, password, email string) string {
2014-11-20 06:17:43 +03:00
addUserMutex.Lock()
defer addUserMutex.Unlock()
2014-11-30 05:18:17 +03:00
2014-08-31 14:50:38 +04:00
for _, user := range conf.Wide.Users {
if user.Name == username {
2014-12-07 06:07:32 +03:00
return userExists
2014-08-31 14:50:38 +04:00
}
2014-12-08 09:02:39 +03:00
if user.Email == email {
return emailExists
}
2014-08-31 14:50:38 +04:00
}
firstUserWorkspace := conf.Wide.GetUserWorkspace(conf.Wide.Users[0].Name)
dir := filepath.Dir(firstUserWorkspace)
workspace := filepath.Join(dir, username)
2014-12-08 09:02:39 +03:00
newUser := conf.NewUser(username, password, email, workspace)
conf.Wide.Users = append(conf.Wide.Users, newUser)
2014-08-31 14:50:38 +04:00
if !conf.Save() {
2014-12-07 06:07:32 +03:00
return userCreateError
2014-08-31 14:50:38 +04:00
}
conf.CreateWorkspaceDir(workspace)
helloWorld(workspace)
2014-11-01 08:35:02 +03:00
conf.UpdateCustomizedConf(username)
http.Handle("/workspace/"+username+"/",
http.StripPrefix("/workspace/"+username+"/", http.FileServer(http.Dir(newUser.GetWorkspace()))))
2014-08-31 14:50:38 +04:00
glog.Infof("Created a user [%s]", username)
2014-12-07 06:07:32 +03:00
return userCreated
2014-08-31 14:50:38 +04:00
}
// helloWorld generates the 'Hello, 世界' source code in workspace/src/hello/main.go.
func helloWorld(workspace string) {
dir := workspace + conf.PathSeparator + "src" + conf.PathSeparator + "hello"
if err := os.MkdirAll(dir, 0755); nil != err {
glog.Error(err)
return
}
fout, err := os.Create(dir + conf.PathSeparator + "main.go")
if nil != err {
glog.Error(err)
os.Exit(-1)
}
fout.WriteString(`package main
import "fmt"
func main() {
fmt.Println("Hello, 世界")
}
`)
fout.Close()
}