func getUserInfoCached(tokens oauth2.Tokens) (userObject map[string]interface{}) { if val, ok := userObjectCache[tokens.Access()]; ok { userObject = val } return }
// CurrentUser returns current signed in user object func CurrentUser(tokens oauth2.Tokens) *User { profile, _ := GoogleGetProfile(tokens.Access()) email := profile.Email name := profile.Name user := User{Email: email} db.Where(&user).First(&user) if user.ID == 0 { db.Unscoped().Where(&user).First(&user) } if len(user.Name) == 0 && len(name) > 0 { user.Name = name db.Save(&user) setting := &Setting{UserID: int(user.ID)} db.Create(setting) } if user.DeletedAt != nil { user.DeletedAt = nil db.Unscoped().Save(&user) if len(user.Username) > 0 { path := filepath.Join(HomeDir(), "app/public/files/"+user.Username) os.Mkdir(path, 0755) } } return &user }
//DomainChecker - check the authenticated users domain to see if it is in the whitelist func DomainChecker(res http.ResponseWriter, tokens oauth2.Tokens) { userInfo := GetUserInfo(tokens) if domain, ok := userInfo["domain"]; !ok || tokens.Expired() || isBlockedDomain(domain.(string)) { res.WriteHeader(FailureStatus) res.Write(AuthFailureResponse) } }
func EnsureSessionVariables(s sessions.Session, t oauth2.Tokens) { userName := s.Get("userName") twitchId := s.Get("twitchId") if userName == nil || twitchId == nil { u, err := GetTwitchUser(t.Access()) if err != nil { log.Fatal(err) } s.Set("userName", u.DisplayName) s.Set("twitchId", u.Id) } }
// github && google && ... func SocialSignIn(tokens oauth2.Tokens) { transport := &oauth.Transport{} transport.Token = &oauth.Token{ AccessToken: tokens.Access(), RefreshToken: tokens.Refresh(), Expiry: tokens.ExpiryTime(), Extra: tokens.ExtraData(), } // Github API refer: https://developer.github.com/v3/users/ // FIXME: need to judge url type GithubUser struct { Id int `json:"id"` Name string `json:"login"` Email string `json:"email"` } // Make the request. scope := "https://api.github.com/user" r, err := transport.Client().Get(scope) if err != nil { log.Error("connect with github error: %s", err) // FIXME: handle error page return } defer r.Body.Close() user := &GithubUser{} err = json.NewDecoder(r.Body).Decode(user) if err != nil { log.Error("Get: %s", err) } log.Info("login: %s", user.Name) // FIXME: login here, user email to check auth, if not registe, then generate a uniq username }
func (a *GitHubAuth) Authenticate(organizations []string, c martini.Context, tokens oauth2.Tokens, w http.ResponseWriter, r *http.Request) { if len(organizations) > 0 { req, err := http.NewRequest("GET", fmt.Sprintf("%s/user/orgs", a.conf.Auth.Info.ApiEndpoint), nil) if err != nil { log.Printf("failed to create a request to retrieve organizations: %s", err) forbidden(w) return } req.SetBasicAuth(tokens.Access(), "x-oauth-basic") client := http.Client{} res, err := client.Do(req) if err != nil { log.Printf("failed to retrieve organizations: %s", err) forbidden(w) return } data, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { log.Printf("failed to read body of GitHub response: %s", err) forbidden(w) return } var info []map[string]interface{} if err := json.Unmarshal(data, &info); err != nil { log.Printf("failed to decode json: %s", err.Error()) forbidden(w) return } for _, userOrg := range info { for _, org := range organizations { if userOrg["login"] == org { return } } } log.Print("not a member of designated organizations") forbidden(w) return } }
// Get the logged in user func GetLoggedInUser(tokens oauth2.Tokens, r render.Render) (int, string) { var url = "https://www.googleapis.com/plus/v1/people/me?access_token=" + tokens.Access() resp, err := http.Get(url) if err != nil { panic(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } return 200, string(body) }
func oauth_get(url string, tokens oauth2.Tokens) []byte { req, err := http.NewRequest("GET", url, nil) if err != nil { log.Fatal(err) } req.Header.Set("Authorization", "Bearer "+tokens.Access()) client := http.Client{} res, err := client.Do(req) if err != nil { log.Fatal(err) } body, err := ioutil.ReadAll(res.Body) res.Body.Close() if err != nil { log.Fatal(err) } return body }
func getUserInfo(tokens oauth2.Tokens) (userObject map[string]interface{}) { url := "https://www.googleapis.com/plus/v1/people/me" token := &goauth2.Token{ AccessToken: tokens.Access(), TokenType: "Bearer", RefreshToken: tokens.Refresh(), Expiry: tokens.ExpiryTime(), } client := OauthConfig.Client(goauth2.NoContext, token) resp, _ := client.Get(url) defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) json.Unmarshal(body, &userObject) addUserObjectToCache(tokens, userObject) return }
/* Middleware to: - Retrieve data from github if user is logged in and data is not stored in sessions - Delete session data if user logged out */ func RequestData(tokens oauth2.Tokens, session sessions.Session) { if !tokens.Expired() && session.Get("username") == nil { access := tokens.Access() req, _ := http.NewRequest("GET", "https://api.github.com/user?access_token="+access, nil) client := &http.Client{} resp, _ := client.Do(req) body, _ := ioutil.ReadAll(resp.Body) parse := map[string]interface{}{} json.Unmarshal([]byte(string(body)), &parse) session.Set("username", parse["login"]) session.Set("user_id", parse["id"]) session.Set("avatar", parse["avatar_url"]) log.Println("retrieved data") } else if tokens.Expired() && session.Get("username") != nil { session.Clear() log.Println("removed data") } }
func addUserObjectToCache(tokens oauth2.Tokens, userObject map[string]interface{}) (err error) { userObjectCache[tokens.Access()] = userObject return }
func (a *GoogleAuth) Authenticate(domain []string, c martini.Context, tokens oauth2.Tokens, w http.ResponseWriter, r *http.Request) { extra := tokens.ExtraData() if _, ok := extra["id_token"]; ok == false { log.Printf("id_token not found") forbidden(w) return } keys := strings.Split(extra["id_token"], ".") if len(keys) < 2 { log.Printf("invalid id_token") forbidden(w) return } data, err := base64Decode(keys[1]) if err != nil { log.Printf("failed to decode base64: %s", err.Error()) forbidden(w) return } var info map[string]interface{} if err := json.Unmarshal(data, &info); err != nil { log.Printf("failed to decode json: %s", err.Error()) forbidden(w) return } if email, ok := info["email"].(string); ok { var user *User if len(domain) > 0 { for _, d := range domain { if strings.Contains(d, "@") { if d == email { user = &User{email} } } else { if strings.HasSuffix(email, "@"+d) { user = &User{email} break } } } } else { user = &User{email} } if user != nil { log.Printf("user %s logged in", email) c.Map(user) } else { log.Printf("email doesn't allow: %s", email) forbidden(w) return } } else { log.Printf("email not found") forbidden(w) return } }