Improve UploadAvatar API.

This commit is contained in:
Yang Luo 2021-04-28 19:02:01 +08:00
parent ee8f2a6046
commit ea9bdbf45e
2 changed files with 16 additions and 11 deletions

View File

@ -17,9 +17,8 @@ package controllers
import (
"encoding/base64"
"encoding/json"
"strconv"
"fmt"
"strings"
"time"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
@ -150,17 +149,17 @@ func (c *ApiController) GetAccount() {
// @router /upload-avatar [post]
func (c *ApiController) UploadAvatar() {
var resp Response
username := c.GetSessionUser()
user := object.GetUser(username)
msg := object.CheckUserLogin(user.Owner+"/"+user.Name, c.Ctx.Request.Form.Get("password"))
if msg != "" {
resp = Response{Status: "error", Msg: "Wrong password"}
username := c.GetSessionUser()
if c.GetSessionUser() == "" {
resp = Response{Status: "error", Msg: "Please sign in first", Data: c.GetSessionUser()}
c.Data["json"] = resp
c.ServeJSON()
return
}
user := object.GetUser(username)
avatarBase64 := c.Ctx.Request.Form.Get("avatarfile")
index := strings.Index(avatarBase64, ",")
if index < 0 || avatarBase64[0:index] != "data:image/png;base64" {
@ -171,16 +170,16 @@ func (c *ApiController) UploadAvatar() {
}
dist, _ := base64.StdEncoding.DecodeString(avatarBase64[index+1:])
msg = object.UploadAvatar(user.Name, dist)
msg := object.UploadAvatar(user.Name, dist)
if msg != "" {
resp = Response{Status: "error", Msg: msg}
c.Data["json"] = resp
c.ServeJSON()
return
}
user.Avatar = object.GetAvatarPath() + user.Name + ".png?time=" + strconv.FormatInt(time.Now().UnixNano(), 10)
user.Avatar = fmt.Sprintf("%s%s.png?time=%s", object.GetAvatarPath(), user.Name, util.GetCurrentUnixTime())
object.UpdateUser(user.Owner+"/"+user.Name, user)
resp = Response{Status: "ok", Msg: "Successfully set avatar"}
resp = Response{Status: "ok", Msg: ""}
c.Data["json"] = resp
c.ServeJSON()
}

View File

@ -1,6 +1,9 @@
package util
import "time"
import (
"strconv"
"time"
)
func GetCurrentTime() string {
timestamp := time.Now().Unix()
@ -8,3 +11,6 @@ func GetCurrentTime() string {
return tm.Format(time.RFC3339)
}
func GetCurrentUnixTime() string {
return strconv.FormatInt(time.Now().UnixNano(), 10)
}