Exemple #1
0
// 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
}
Exemple #2
0
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
	}
}