All checks were successful
continuous-integration/drone/push Build is passing
101 lines
2.1 KiB
Go
101 lines
2.1 KiB
Go
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, role) values ($1, $2, $3) returning id`,
|
|
user.Username, encryptedPassowrd, user.Role)
|
|
|
|
err = ret.Scan(&user.Id)
|
|
if err != nil {
|
|
c.AbortWithError(401, err)
|
|
return
|
|
}
|
|
|
|
c.JSON(200, gin.H{})
|
|
|
|
}
|