-
Notifications
You must be signed in to change notification settings - Fork 0
/
oauth.go
74 lines (56 loc) · 1.79 KB
/
oauth.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
62
63
64
65
66
67
68
69
70
71
72
73
74
package adapter
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/scarlet0725/prism-api/adapter/util"
"github.com/scarlet0725/prism-api/model"
"github.com/scarlet0725/prism-api/usecase"
)
type OAuthAdapter interface {
GoogleOAuthCallback(ctx *gin.Context)
GoogleLinkage(ctx *gin.Context)
}
type oAuthAdapter struct {
oauth usecase.OAuth
}
func NewOAuthAdapter(oauthUsecase usecase.OAuth) OAuthAdapter {
return &oAuthAdapter{
oauth: oauthUsecase,
}
}
func (a *oAuthAdapter) GoogleOAuthCallback(ctx *gin.Context) {
var req model.GoogleOauthCallback
if err := ctx.ShouldBindQuery(&req); err != nil {
ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"ok": false, "error": "invalid request"})
return
}
err := a.oauth.GoogleOAuthCallback(&req)
if err != nil {
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"ok": false, "error": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"ok": true, "message": "success"})
}
func (a *oAuthAdapter) GoogleLinkage(ctx *gin.Context) {
var appErr *model.AppError
user, err := util.GetUserFromContext(ctx)
if err != nil {
if ok := errors.As(err, &appErr); ok {
ctx.AbortWithStatusJSON(appErr.Code, gin.H{"ok": false, "error": appErr.Msg})
return
}
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"ok": false, "error": "Invalid api Key"})
return
}
resp, err := a.oauth.GoogleLinkage(user)
if err != nil {
if ok := errors.As(err, &appErr); ok {
ctx.AbortWithStatusJSON(appErr.Code, gin.H{"ok": false, "error": appErr.Msg})
return
}
ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"ok": false, "error": "Internal Server Error"})
return
}
ctx.JSON(http.StatusOK, gin.H{"ok": true, "authenticate_url": resp.AuthURL, "message": "Please authenticate with google"})
}