-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
164 lines (135 loc) Β· 3.76 KB
/
main.go
File metadata and controls
164 lines (135 loc) Β· 3.76 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
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
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/gin-gonic/gin"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
// Credentials json configuration file rappresentation
type Credentials struct {
Cid string `json:"cid"`
Csecret string `json:"csecret"`
}
// OAuthUser is the OAuth user rappresentation
type OAuthUser struct {
Sub string `json:"sub"`
Name string `json:"name"`
GivenName string `json:"given_name"`
FamilyName string `json:"family_name"`
Picture string `json:"picture"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Locale string `json:"locale"`
}
// User in database rappresentation
type User struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at"`
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
Email string `json:"email"`
}
var cred Credentials
var conf *oauth2.Config
var state string
var db *gorm.DB
func initDb() *gorm.DB {
dbi, err := gorm.Open("postgres", "host=goauthdb port=5432 user=admin dbname=goauthdb password=123 sslmode=disable")
if err != nil {
panic(err.Error())
}
db = dbi
migration(db)
return db
}
func migration(db *gorm.DB) {
db.AutoMigrate(&User{})
}
func init() {
initDb()
file, err := ioutil.ReadFile("./creds.json")
if err != nil {
log.Printf("File error: %v\n", err)
os.Exit(1)
}
json.Unmarshal(file, &cred)
var ru string = os.Getenv("URL") + "v1/oauth?type=google"
conf = &oauth2.Config{
ClientID: cred.Cid,
ClientSecret: cred.Csecret,
RedirectURL: ru,
Scopes: []string{
"https://www.googleapis.com/auth/userinfo.email", // You have to select your own scope from here -> https://developers.google.com/identity/protocols/googlescopes#google_sign-in
"https://www.googleapis.com/auth/userinfo.profile",
},
Endpoint: google.Endpoint,
}
}
func indexHandler(c *gin.Context) {
c.String(http.StatusOK, "Welcome to goauth API")
}
func getLoginURL(state string) string {
return conf.AuthCodeURL(state)
}
func authHandler(c *gin.Context) {
p := c.Request.URL.Query()
types := p["type"]
if types == nil || len(types) <= 0 || len(types[0]) <= 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing auth type"})
return
}
authType := types[0]
if authType != "google" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Not valid auth type"})
return
}
tok, err := conf.Exchange(oauth2.NoContext, c.Query("code"))
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
client := conf.Client(oauth2.NoContext, tok)
userinfo, err := client.Get("https://www.googleapis.com/oauth2/v3/userinfo")
if err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
defer userinfo.Body.Close()
data, _ := ioutil.ReadAll(userinfo.Body)
log.Println("Email body: ", string(data))
var ou OAuthUser
if err := json.Unmarshal(data, &ou); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"Error": "parsing OauthUser", "e": err.Error()})
return
}
var u User
db.Where("email = ?", ou.Email).First(&u)
if u.ID > 0 {
c.JSON(http.StatusOK, gin.H{"data": u, "exists": "yes"})
return
}
u.Email = ou.Email
u.Firstname = ou.GivenName
u.Lastname = ou.FamilyName
db.Save(&u)
c.JSON(http.StatusOK, gin.H{"data": u, "exists": "no"})
}
func loginHandler(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"url": getLoginURL(state)})
}
func main() {
router := gin.Default()
router.GET("/goauth", indexHandler)
router.GET("/goauth/login", loginHandler)
router.GET("/goauth/v1/oauth", authHandler)
router.Run(":8080")
}