-
Notifications
You must be signed in to change notification settings - Fork 2
/
oauth_controller.go
61 lines (52 loc) · 1.62 KB
/
oauth_controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package controllers
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/logger"
"gozen/config"
"gozen/models"
"gozen/oauth"
)
// 認証コントローラー
type OAuthController struct {
oauth.User
}
func NewOauthController(user oauth.User) OAuthController {
return OAuthController{user}
}
// ログインへリダイレクトを行う
func (self OAuthController) Login() gin.HandlerFunc {
return jsonController(func(c *gin.Context) (interface{}, models.Error) {
if self.User.GetClientID() == nil {
return nil, models.NewError(http.StatusInternalServerError, "client_id has not been set.")
}
if self.User.GetClientSecret() == nil {
return nil, models.NewError(http.StatusInternalServerError, "client_secret has not been set.")
}
url := self.User.GenerateLoginUrl()
c.Redirect(http.StatusTemporaryRedirect, url)
return nil, nil
})
}
// CallBack処理を行う
func (self OAuthController) CallBack() gin.HandlerFunc {
return jsonController(func(c *gin.Context) (interface{}, models.Error) {
logger.Infoln(c.Request.URL)
user, err := self.User.Callback(c.Query("state"), c.Query("code"))
if err != nil {
return nil, models.NewError(http.StatusBadRequest, err.Error())
}
return commonOauthController(c, user)
})
}
func commonOauthController(c *gin.Context, user oauth.User) (interface{}, models.Error) {
token, err := models.NewUser().Auth(user)
if err != nil {
return nil, models.NewError(http.StatusBadRequest, err.Error())
}
url := fmt.Sprintf("%s?token=%s", config.Oauth.AfterOauthUrl, token)
logger.Infoln(url)
c.Redirect(http.StatusTemporaryRedirect, url)
return nil, nil
}