-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserHandler.go
More file actions
91 lines (74 loc) · 1.91 KB
/
userHandler.go
File metadata and controls
91 lines (74 loc) · 1.91 KB
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
package main
/*
The userHandler file is used as a user manager.
Here you have the main user actions.
Need to rewrite the requests response.
*/
import (
"fmt"
"net/http"
"net/url"
"strings"
"github.com/jinzhu/gorm"
"github.com/pressly/chi"
"github.com/vesli/ntm/config"
"github.com/vesli/ntm/helper"
)
// Token structure, passing access token from body response to the facebook graph API
type Token struct {
AccessToken string `json:"access_token"`
}
func valueFromContext(r *http.Request) (*config.Config, *gorm.DB) {
conf := r.Context().Value(configuration).(*config.Config)
DB := r.Context().Value(psqlDB).(*gorm.DB)
return conf, DB
}
/* Facebook login from URL */
func getUserFromToken(t *Token, conf *config.Config) (*User, error) {
u := &User{}
urlParams := make(url.Values)
urlParams.Add("access_token", t.AccessToken)
urlParams.Add("fields", conf.FBParams)
r, err := http.Get(fmt.Sprintf("%s?%s", conf.FBURL, urlParams.Encode()))
if err != nil {
return nil, err
}
err = helper.DecodeBody(&u, r.Body)
if err != nil {
return nil, err
}
return u, nil
}
func getUserFromDB(w http.ResponseWriter, r *http.Request) {
_, db := valueFromContext(r)
userID := strings.Title(chi.URLParam(r, "id"))
u := &User{}
err := db.First(&u, userID).Error
if err != nil {
helper.WriteJSON(w, err, http.StatusBadRequest)
return
}
helper.WriteJSON(w, u, http.StatusOK)
}
func registerAndLogginUser(w http.ResponseWriter, r *http.Request) {
t := &Token{}
re := helper.DecodeBody(&t, r.Body)
if re != nil {
helper.WriteJSON(w, re, http.StatusBadRequest)
return
}
conf, db := valueFromContext(r)
u, err := getUserFromToken(t, conf)
if err != nil {
helper.WriteJSON(w, err, http.StatusBadRequest)
return
}
if !u.userAlreadyExists(db) {
err = db.Create(&u).Error
if err != nil {
helper.WriteJSON(w, err, http.StatusInternalServerError)
return
}
}
helper.WriteJSON(w, u, http.StatusOK)
}