go-gallery/routers/account/account.go

98 lines
1.7 KiB
Go

package account
import (
"crypto/rand"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"log"
"reflect"
"strings"
"git.trj.tw/golang/go-gallery/modules/memstore"
"git.trj.tw/golang/go-gallery/models"
"git.trj.tw/golang/go-gallery/modules/context"
"git.trj.tw/golang/go-gallery/modules/utils"
"golang.org/x/crypto/pbkdf2"
)
// UserLogin route
func UserLogin(c *context.Context) {
loginArg := struct {
Account string `form:"account" json:"account" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}{
Account: "",
Password: "",
}
err := c.BindData(&loginArg)
if err != nil {
c.DataFormat(nil)
return
}
acc, err := models.GetAccount(loginArg.Account)
if err != nil {
log.Println(err)
c.ServerError(nil)
return
}
if acc == nil {
c.NotFound("User not found")
return
}
strs := strings.Split(acc.Password, ".")
if len(strs) != 2 {
c.ServerError("store pass format error")
return
}
b, err := hex.DecodeString(strs[0])
if err != nil {
c.ServerError(nil)
return
}
hashPass, err := hex.DecodeString(strs[1])
if err != nil {
c.ServerError(nil)
return
}
enc := pbkdf2.Key([]byte(loginArg.Password), b, 2048, 64, sha512.New)
if enc == nil || !reflect.DeepEqual(enc, hashPass) {
c.DataFormat("password error")
return
}
res := utils.ToMap(acc)
m := make(map[string]interface{})
m["user"] = res
jsonStr, err := json.Marshal(m)
if err != nil {
c.ServerError(nil)
return
}
tByte := make([]byte, 20)
_, err = rand.Read(tByte)
if err != nil {
c.ServerError(nil)
return
}
err = memstore.RedisSet("golang", hex.EncodeToString(tByte), string(jsonStr), 600)
if err != nil {
c.ServerError(nil)
}
m["token"] = hex.EncodeToString(tByte)
c.Success(m)
}