first commit

This commit is contained in:
2022-12-13 07:42:44 +08:00
commit 7ef2644e20
46 changed files with 7810 additions and 0 deletions

100
pkg/api/handle_user.go Normal file
View File

@@ -0,0 +1,100 @@
package api
import (
"time"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
type User struct {
Id int64 `json:"id"`
Username string `json:"username"`
Password string `json:"password"`
Balance string `json:"balance"`
Location string `json:"location"`
Role int64 `json:"role"`
RegisterTime time.Time `json:"register_time"`
}
var SESSION_NAME = "ais"
func handelLogout(c *gin.Context) {
session := sessions.Default(c)
session.Clear()
session.Save()
c.JSON(200, gin.H{})
}
func handelGetLoginSession(c *gin.Context) {
session := sessions.Default(c)
userId := session.Get("userid")
if userId == nil {
c.JSON(200, gin.H{})
return
}
user := &User{}
row := db.QueryRow(`select id, username, balance, location, role from users where id=$1`, userId)
err := row.Scan(&user.Id, &user.Username, &user.Balance, &user.Location, &user.Role)
if err != nil {
c.AbortWithError(403, err)
return
}
c.JSON(200, user)
}
func handelLogin(c *gin.Context) {
user := &User{}
err := c.BindJSON(user)
if err != nil {
c.AbortWithError(500, err)
return
}
var encryptedPassowrd string
row := db.QueryRow(`select id, username, balance, location, role, password from users where username=$1`,
user.Username)
err = row.Scan(&user.Id, &user.Username, &user.Balance, &user.Location, &user.Role, &encryptedPassowrd)
if err != nil {
c.AbortWithError(403, err)
return
}
// validate password
err = ComparePassword(encryptedPassowrd, user.Password)
if err != nil {
c.AbortWithError(403, err)
return
}
// set session
session := sessions.Default(c)
session.Set("userid", user.Id)
session.Save()
c.JSON(200, user)
}
func handelRegister(c *gin.Context) {
user := &User{}
err := c.BindJSON(user)
if err != nil {
c.AbortWithError(401, err)
return
}
encryptedPassowrd := EncryptPassword(user.Password)
ret := db.QueryRow(`insert into users(username, password) values ($1, $2) returning id`,
user.Username, encryptedPassowrd)
err = ret.Scan(&user.Id)
if err != nil {
c.AbortWithError(401, err)
return
}
c.JSON(200, gin.H{})
}