-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFacebookAuthController.go
244 lines (204 loc) · 7.13 KB
/
FacebookAuthController.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package user
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
jwt "github.com/dgrijalva/jwt-go"
"github.com/go-bolo/bolo"
user_models "github.com/go-bolo/user/models"
user_oauth2_password "github.com/go-bolo/user/oauth2_password"
"github.com/labstack/echo/v4"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"golang.org/x/oauth2/facebook"
"gorm.io/gorm"
)
type FacebookAuthController struct {
}
func (ctl *FacebookAuthController) LoginWithFacebookAppCode(c echo.Context) error {
ctx := c.(*bolo.RequestContext)
var OAuth2Config = GetFacebookOAuthConfig(ctx)
if OAuth2Config.ClientID == "" || OAuth2Config.ClientSecret == "" {
return &bolo.HTTPError{
Code: http.StatusNotFound,
Message: "facebook auth configuration not set",
Internal: errors.New("facebook auth configuration not set"),
}
}
ctx.SetResponseContentType("application/json")
var body LoginWithFacebookAppCodeBodyRequest
if err := c.Bind(&body); err != nil {
if _, ok := err.(*echo.HTTPError); ok {
return err
}
return c.NoContent(http.StatusNotFound)
}
token, err := OAuth2Config.Exchange(context.Background(), body.Code)
if err != nil || token == nil {
logrus.WithFields(logrus.Fields{
"err": err,
}).Error("LoginWithFacebookAppCode: error on exchange token")
return &bolo.HTTPError{
Code: http.StatusUnauthorized,
Message: "Invalid token",
Internal: fmt.Errorf("error on exchange token: %w", err),
}
}
fbUserDetails, fbUserDetailsError := GetUserInfoFromFacebook(token.AccessToken, ctx)
if fbUserDetailsError != nil {
logrus.WithFields(logrus.Fields{
"err": err,
}).Error("LoginWithFacebookAppCode: error on get user info from facebook")
return &bolo.HTTPError{
Code: http.StatusUnauthorized,
Message: "Invalid token",
Internal: fmt.Errorf("error on get user info from facebook: %w", fbUserDetailsError),
}
}
u, authTokenError := FindOrCreateUserFromFacebook(fbUserDetails, ctx)
if authTokenError != nil {
d, _ := json.Marshal(fbUserDetails)
logrus.WithFields(logrus.Fields{
"err": authTokenError,
"fbUserDetails": string(d),
"u": u,
}).Error("LoginWithFacebookAppCode: error on FindOrCreateUserFromFacebook")
return &bolo.HTTPError{
Code: http.StatusUnauthorized,
Message: "Invalid token",
Internal: fmt.Errorf("FindOrCreateUserFromFacebook: %w", authTokenError),
}
}
// Authenticate user:
data, err := user_oauth2_password.Oauth2GenerateAndSaveToken(ctx, u)
if err != nil {
logrus.WithFields(logrus.Fields{
"err": err,
}).Error("LoginWithFacebookAppCode: error on generate and save token")
return &bolo.HTTPError{
Code: http.StatusBadRequest,
Message: "Invalid token",
Internal: fmt.Errorf("error on generate and save token: %w", err),
}
}
resp := oauth2PasswordJSONResponse{
AccessToken: &data.AccessToken,
RefreshToken: &data.RefreshToken,
ExpiresIn: &data.ExpiresIn,
User: u,
}
return c.JSON(200, &resp)
}
type NewFacebookAuthControllerCFG struct {
App bolo.App
}
func NewFacebookAuthController(cfg *NewFacebookAuthControllerCFG) *FacebookAuthController {
return &FacebookAuthController{}
}
// ErrorResponse is struct for sending error message with code.
type ErrorResponse struct {
Code int
Message string
}
// SuccessResponse is struct for sending error message with code.
type SuccessResponse struct {
Code int
Message string
Response interface{}
}
// Claims is a struct that will be encoded to a JWT.
// jwt.StandardClaims is an embedded type to provide expiry time
type Claims struct {
Email string
jwt.StandardClaims
}
// UserDetails is struct used for user details
type UserDetails struct {
Name string
Email string
Password string
}
// FacebookUserDetails is struct used for user details
type FacebookUserDetails struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Picture *FacebookUserPicture `json:"picture"`
}
type FacebookUserPicture struct {
Data struct {
Height int `json:"height"`
IsSilhouette bool `json:"is_silhouette"`
URL string `json:"url"`
Width int `json:"width"`
} `json:"data"`
}
type LoginWithFacebookAppCodeBodyRequest struct {
Code string `json:"code"`
RedirectUri string `json:"redirect_uri"`
}
// GetFacebookOAuthConfig will return the config to call facebook Login
func GetFacebookOAuthConfig(ctx *bolo.RequestContext) *oauth2.Config {
cfgs := ctx.App.GetConfiguration()
return &oauth2.Config{
ClientID: cfgs.Get("SITE_FACEBOOK_APP_ID"),
ClientSecret: cfgs.Get("FACEBOOK_CLIENT_SECRET"),
Endpoint: facebook.Endpoint,
RedirectURL: cfgs.Get("FACEBOOK_REDIRECT_URI"),
}
}
// GetUserInfoFromFacebook will return information of user which is fetched from facebook
func GetUserInfoFromFacebook(token string, ctx *bolo.RequestContext) (FacebookUserDetails, error) {
var fbUserDetails FacebookUserDetails
facebookUserDetailsRequest, err := http.NewRequest("GET", "https://graph.facebook.com/me?fields=id,name,email&access_token="+token, nil)
facebookUserDetailsResponse, facebookUserDetailsResponseError := http.DefaultClient.Do(facebookUserDetailsRequest)
if err != nil {
return FacebookUserDetails{}, fmt.Errorf("error occurred while getting information from facebook: %w", err)
}
if facebookUserDetailsResponseError != nil {
return FacebookUserDetails{}, fmt.Errorf("error occurred while getting information from facebook response: %w", facebookUserDetailsResponseError)
}
decoder := json.NewDecoder(facebookUserDetailsResponse.Body)
decoderErr := decoder.Decode(&fbUserDetails)
defer facebookUserDetailsResponse.Body.Close()
if decoderErr != nil {
return FacebookUserDetails{}, fmt.Errorf("error occurred while decoding information from facebook: %w", decoderErr)
}
return fbUserDetails, nil
}
// SignInUser Used for Signing In the Users
func FindOrCreateUserFromFacebook(facebookUserDetails FacebookUserDetails, ctx *bolo.RequestContext) (*user_models.UserModel, error) {
if facebookUserDetails.Email == "" {
return nil, errors.New("FindOrCreateUserFromFacebook last name can't be empty")
}
if facebookUserDetails.Name == "" {
return nil, errors.New("FindOrCreateUserFromFacebook password can't be empty")
}
u := user_models.UserModel{}
err := user_models.UserFindOneByUsername(facebookUserDetails.Email, &u)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.New("FindOrCreateUserFromFacebook user not found")
}
if u.ID == 0 {
// user not found, create new user
u.Username = facebookUserDetails.ID
u.Email = facebookUserDetails.Email
u.DisplayName = facebookUserDetails.Name
u.FullName = facebookUserDetails.Name
u.Active = true
u.AcceptTerms = false
err = u.Save(ctx)
if err != nil {
return nil, fmt.Errorf("FindOrCreateUserFromFacebook error on save user: %w", err)
}
}
return &u, nil
}
type oauth2PasswordJSONResponse struct {
AccessToken *string `json:"access_token"`
RefreshToken *string `json:"refresh_token"`
ExpiresIn *int64 `json:"expires_in"`
User *user_models.UserModel `json:"user"`
}