Skip to content

Commit

Permalink
feat: updateLoginMethod
Browse files Browse the repository at this point in the history
  • Loading branch information
hiwatee committed Jan 9, 2021
1 parent 2760415 commit 7e47493
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 14 deletions.
33 changes: 21 additions & 12 deletions controllers/common.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
package controllers

import (
"beego-members-api/models"

"github.com/beego/beego/v2/client/orm"
)

// DefaultSuccessResponse is ...
type DefaultSuccessResponse struct {
// TODO: enumをサポートしたらenumに変更する
Expand All @@ -12,18 +18,21 @@ type DefaultErrorResponse struct {
Message string `json:"message" required:"true" example:"snaked_params" description:"result status"`
}

// func IsUserLoggedIn(c *BaseController) {
// GetCurrentUser(c)
// log.Print("-----------------")
// log.Print("here")
// log.Print("-----------------")
// }
// IsUserLoggedIn is ...
func IsUserLoggedIn(userID int) bool {
if userID == 0 {
return false
}
return true
}

// GetCurrentUser is ...
func GetCurrentUser(token string) {
// token := c.Ctx.GetCookie("access_token")
// log.Print("-----------------")
// log.Print(token)
// log.Print("-----------------")

func GetCurrentUser(token string) int {
var accessToken models.AccessToken
o := orm.NewOrm()
err := o.QueryTable("access_token").Filter("token", token).One(&accessToken)
if err == orm.ErrNoRows {
return 0
}
return int(accessToken.User.Id)
}
2 changes: 1 addition & 1 deletion controllers/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,6 @@ func (c *LoginController) Login() {
c.Data["json"] = mes
c.Ctx.SetCookie("token", token)
// swaggerでの開発確認用でcookieにもセットしています。
c.Ctx.SetCookie("access_token", token)
c.Ctx.SetCookie("access_token", accessToken)
c.ServeJSON()
}
9 changes: 8 additions & 1 deletion controllers/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,14 @@ func (c *UserController) URLMapping() {
// Prepare ...
func (c *UserController) Prepare() {
token := c.Ctx.GetCookie("access_token")
GetCurrentUser(token)
if token == "" {
token = c.Ctx.Request.Header.Get("access_token")
}
if !IsUserLoggedIn(GetCurrentUser(token)) {
c.Ctx.Output.SetStatus(401)
c.Data["json"] = DefaultErrorResponse{Message: "user_un_authorized"}
c.ServeJSON()
}
}

// Post ...
Expand Down

0 comments on commit 7e47493

Please sign in to comment.