本文整理汇总了Golang中github.com/markbates/goth/gothic.CompleteUserAuth函数的典型用法代码示例。如果您正苦于以下问题:Golang CompleteUserAuth函数的具体用法?Golang CompleteUserAuth怎么用?Golang CompleteUserAuth使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了CompleteUserAuth函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: authCallback
func authCallback(res http.ResponseWriter, req *http.Request) {
// print our state string to the console. Ideally, you should verify
// that it's the same string as the one you set in `setState`
fmt.Println("State: ", gothic.GetState(req))
fmt.Println("request method: " + req.Method)
user, err := gothic.CompleteUserAuth(res, req)
if err != nil {
fmt.Fprintln(res, err)
return
}
//t, _ := template.New("foo").Parse(userTemplate)
account := &models.Account{user.Email, ""}
fmt.Println(account.CheckExist())
//if everything is fine, set the session for the current user
sess, err := globalSessions.SessionStart(res, req)
if err != nil {
fmt.Println("set error,", err)
}
defer sess.SessionRelease(res)
err = sess.Set("username", user.Email)
if err != nil {
fmt.Println("set error,", err)
}
//set the status of the user
sess.Set("logged", "true")
http.Redirect(res, req, "/user/"+user.Email, http.StatusFound)
//t.Execute(res, user)
}
示例2: AuthCallback
func AuthCallback(w http.ResponseWriter, r *http.Request) {
observedState := []byte(gothic.GetState(r))
expectedState := state_hash
if subtle.ConstantTimeCompare(observedState, expectedState) != 1 {
http.Error(w, "State sent did not match state received.", http.StatusBadRequest)
log.Info("Observed and expected states do not match.")
return
}
user, err := gothic.CompleteUserAuth(w, r)
if err != nil {
log.Warn(w, err)
return
}
t, err := template.ParseFiles("oauth/templates/user.html.tmpl")
if err != nil {
log.Warn(w, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
t.Execute(w, user)
}
示例3: CallbackHandler
func CallbackHandler(response http.ResponseWriter, request *http.Request) {
session, err := Store.Get(request, "brewlog")
if err != nil {
http.Error(response, err.Error(), 500)
return
}
fmt.Println(gothic.GetState(request))
gUser, err := gothic.CompleteUserAuth(response, request)
if err != nil {
fmt.Println(response, err)
return
}
user, err := models.FindOrCreateUser(&gUser)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(user.Name)
session.Values["user"] = user
err = session.Save(request, response)
if err != nil {
fmt.Println(err.Error())
}
http.Redirect(response, request, "/", http.StatusFound)
}
示例4: HandleAuthCallback
func HandleAuthCallback(w http.ResponseWriter, r *http.Request) {
ctx := GetContext(r)
if ctx.Account != nil {
http.Redirect(w, r, "/organizations", http.StatusSeeOther)
return
}
user, err := gothic.CompleteUserAuth(w, r)
if err != nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
acc, err := data.GetAccountEmail(user.Email)
catch(r, err)
if acc == nil {
accEmail, err := data.NewAccountEmail(user.Email)
catch(r, err)
accEmail.Primary = true
accEmail.Verified = true
accEmail.VerifiedAt = time.Now()
nAcc := data.Account{}
nAcc.Emails = append(nAcc.Emails, accEmail)
err = nAcc.Put()
acc = &nAcc
}
ctx.Session.Values["accountID"] = acc.ID.Hex()
ctx.Session.Save(r, w)
http.Redirect(w, r, "/organizations", http.StatusSeeOther)
}
示例5: loginHandler
// loginHandlerはサードパーティへのログインの処理を受け持ちます
// パスの形式: /auth/{action}/{provider}
func loginHandler(w http.ResponseWriter, r *http.Request) {
action := r.URL.Query().Get(":action")
provider := r.URL.Query().Get(":provider")
switch action {
case "login":
gothic.BeginAuthHandler(w, r)
log.Println("TODO: ログイン処理", provider)
case "callback":
// print our state string to the console. Ideally, you should verify
// that it's the same string as the one you set in `setState`
fmt.Println("State: ", gothic.GetState(r))
user, err := gothic.CompleteUserAuth(w, r)
if err != nil {
log.Fatal("CompleteUserAuth error: ", err)
return
}
authCookieValue := base64.StdEncoding.EncodeToString([]byte(user.Name))
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: authCookieValue,
Path: "/",
})
fmt.Println(user)
w.Header().Set("Location", "/chat")
w.WriteHeader(http.StatusTemporaryRedirect)
default:
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "アクション%sには非対応です", action)
}
}
示例6: providerCallback
func providerCallback(h *helios.Engine, g *GithubService) gin.HandlerFunc {
return func(c *gin.Context) {
var user User
// Run user auth using the gothic library
githubUser, err := gothic.CompleteUserAuth(c.Writer, c.Request)
if err != nil {
h.Warn("Failed to create user from callback", "error", err.Error())
}
user.Username = githubUser.RawData["login"].(string)
user.AccessToken = githubUser.AccessToken
// If the user doesn't exist yet
if _, ok := g.Users[user.Username]; !ok {
userFile, err := os.OpenFile("users.csv", os.O_APPEND|os.O_WRONLY, 0644)
defer userFile.Close()
_, err = userFile.WriteString(fmt.Sprintf("%s,%s\n", user.Username, user.AccessToken))
if err != nil {
h.Error("Failed to write new users to CSV", "error", err.Error())
}
g.Users[user.Username] = user
// startUser(user)
} else {
h.Info("User already exists")
}
c.JSON(200, user)
}
}
示例7: callbackAuthHandler
func callbackAuthHandler(res http.ResponseWriter, req *http.Request) {
user, err := gothic.CompleteUserAuth(res, req)
if err != nil {
fmt.Fprintln(res, err)
return
}
t, _ := template.New("userinfo").Parse(userTemplate)
t.Execute(res, user)
}
示例8: AuthCallback
func (s *Server) AuthCallback(c *gin.Context) {
fn := gothic.GetProviderName
gothic.GetProviderName = func(req *http.Request) (string, error) {
provider := c.Params.ByName("provider")
if provider == "" {
return fn(req)
}
return provider, nil
}
provider, _ := gothic.GetProviderName(c.Request)
u, err := gothic.CompleteUserAuth(c.Writer, c.Request)
if err != nil {
c.String(400, err.Error())
return
}
ctx, cancel := DefaultTimeoutContext()
defer cancel()
authinfo := &pb.OAuthUser{
UserId: u.UserID,
Name: u.Name,
NickName: u.NickName,
Email: u.Email,
AccessToken: u.AccessToken,
AccessTokenSecret: u.AccessTokenSecret,
Provider: provider,
}
profile, err := s.CurrentUser(c)
if err != nil {
c.Fail(500, err)
return
}
authinfo.Uuid = profile.Uuid
profile, err = s.client.PutOAuth(ctx, authinfo)
if RequestError(c, err) {
return
}
// Only allow login from google
// Twitter only for importing feed
if provider == "google" {
sess := sessions.Default(c)
sess.Set("user_id", u.UserID)
sess.Set("uuid", profile.Uuid)
sess.Save()
}
next := extractNextPath(c.Request.URL.Query().Get("state"))
if next == "/" && provider == "twitter" {
next = "/account/import"
}
http.Redirect(c.Writer, c.Request, next, http.StatusFound)
}
示例9: loginHandler
// loginHandlerはサードパーティへのログインの処理を受け持ちます
// パスの形式: /auth/{action}/{provider}
func loginHandler(w http.ResponseWriter, r *http.Request) {
action := r.URL.Query().Get(":action")
// provider := r.URL.Query().Get(":provider")
switch action {
case "login":
gothic.BeginAuthHandler(w, r)
case "callback":
// print our state string to the console. Ideally, you should verify
// that it's the same string as the one you set in `setState`
fmt.Println("State: ", gothic.GetState(r))
githubUser, err := gothic.CompleteUserAuth(w, r)
if err != nil {
log.Fatal("CompleteUserAuth error: ", err)
return
}
// ユーザーの保存
var user User
err = mapstructure.Decode(githubUser.RawData, &user)
if err != nil {
log.Fatal("mapstructure error: ", err)
return
}
session, err := mgo.Dial("mongodb://localhost")
if err != nil {
log.Fatal("mgo database dial error:", err)
return
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("donuts_tech_calendar").C("users")
err = user.FindOrCreate(c)
if err != nil {
log.Fatal("user.FindOrCreate error:", err)
return
}
authCookieValue := base64.StdEncoding.EncodeToString([]byte(user.UserName))
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: authCookieValue,
Path: "/",
})
w.Header().Set("Location", "/index#/chat")
w.WriteHeader(http.StatusTemporaryRedirect)
default:
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "アクション%sには非対応です", action)
}
}
示例10: callbackPageHandler
func callbackPageHandler(res http.ResponseWriter, req *http.Request) {
// print our state string to the console
fmt.Println("State: " + gothic.GetState(req))
user, err := gothic.CompleteUserAuth(res, req)
if err != nil {
fmt.Fprintln(res, err)
return
}
t, _ := template.New("foo").Parse(userTemplate)
t.Execute(res, user)
}
示例11: ServeHTTP
func (ac *AuthCallback) ServeHTTP(w http.ResponseWriter, r *http.Request) {
session, err := gothic.Store.Get(r, "doit-server")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var isCLIAuth bool
id := session.Values["current-auth"].(string)
if _, ok := session.Values["cli-auth"]; ok {
isCLIAuth = true
}
user, err := gothic.CompleteUserAuth(w, r)
if !isCLIAuth {
c := ac.consumers.Get(id)
if err != nil {
c <- Consumer{
ID: id,
Err: err.Error(),
Message: "unble to complete authorization",
}
return
}
c <- Consumer{
ID: id,
AccessToken: user.AccessToken,
}
fmt.Fprintf(w, updateTemplate)
return
}
if err != nil {
fmt.Fprintln(w, "Unable to retrieve access token")
delete(session.Values, "cli-auth")
_ = session.Save(r, w)
return
}
delete(session.Values, "cli-auth")
_ = session.Save(r, w)
t, _ := template.New("cliTemplate").Parse(cliTemplate)
t.Execute(w, user)
}
示例12: handleSocialLogin
func handleSocialLogin(rw http.ResponseWriter, req *http.Request) {
log.Println(gothic.GetState(req))
socialUser, err := gothic.CompleteUserAuth(rw, req)
if err != nil {
log.Println(err)
http.Error(rw, err.Error(), http.StatusBadRequest)
return
}
user := auth.User{}
user.UserID = socialUser.UserID
user.Email = socialUser.Email
log.Println(socialUser.UserID)
log.Println(socialUser.AccessToken)
log.Println(socialUser.NickName)
}
示例13: main
func main() {
goth.UseProviders(
twitter.New(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),
// If you'd like to use authenticate instead of authorize in Twitter provider, use this instead.
// twitter.NewAuthenticate(os.Getenv("TWITTER_KEY"), os.Getenv("TWITTER_SECRET"), "http://localhost:3000/auth/twitter/callback"),
facebook.New(os.Getenv("FACEBOOK_KEY"), os.Getenv("FACEBOOK_SECRET"), "http://localhost:3000/auth/facebook/callback"),
gplus.New(os.Getenv("GPLUS_KEY"), os.Getenv("GPLUS_SECRET"), "http://localhost:3000/auth/gplus/callback"),
github.New(os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"), "http://localhost:3000/auth/github/callback"),
spotify.New(os.Getenv("SPOTIFY_KEY"), os.Getenv("SPOTIFY_SECRET"), "http://localhost:3000/auth/spotify/callback"),
linkedin.New(os.Getenv("LINKEDIN_KEY"), os.Getenv("LINKEDIN_SECRET"), "http://localhost:3000/auth/linkedin/callback"),
lastfm.New(os.Getenv("LASTFM_KEY"), os.Getenv("LASTFM_SECRET"), "http://localhost:3000/auth/lastfm/callback"),
twitch.New(os.Getenv("TWITCH_KEY"), os.Getenv("TWITCH_SECRET"), "http://localhost:3000/auth/twitch/callback"),
dropbox.New(os.Getenv("DROPBOX_KEY"), os.Getenv("DROPBOX_SECRET"), "http://localhost:3000/auth/dropbox/callback"),
)
// Assign the GetState function variable so we can return the
// state string we want to get back at the end of the oauth process.
// Only works with facebook and gplus providers.
gothic.GetState = func(req *http.Request) string {
// Get the state string from the query parameters.
return req.URL.Query().Get("state")
}
p := pat.New()
p.Get("/auth/{provider}/callback", func(res http.ResponseWriter, req *http.Request) {
// print our state string to the console
fmt.Println(gothic.GetState(req))
user, err := gothic.CompleteUserAuth(res, req)
if err != nil {
fmt.Fprintln(res, err)
return
}
t, _ := template.New("foo").Parse(userTemplate)
t.Execute(res, user)
})
p.Get("/auth/{provider}", gothic.BeginAuthHandler)
p.Get("/", func(res http.ResponseWriter, req *http.Request) {
t, _ := template.New("foo").Parse(indexTemplate)
t.Execute(res, nil)
})
http.ListenAndServe(":3000", p)
}
示例14: providerCallback
func providerCallback(c *gin.Context) {
// Run user auth using the gothic library
user, err := gothic.CompleteUserAuth(c.Writer, c.Request)
if err != nil {
logging.ErrorWithTags([]string{"github", "api"}, "Failed to create user from callback", err.Error())
}
u := User{}
err = u.GetByUsername(user.RawData["login"].(string))
if err != nil {
if err != sql.ErrNoRows {
logging.ErrorWithTags([]string{"api"}, "Failed to read from user table", err.Error())
return
}
}
//Add user to the user table
u.Name = user.Name
u.Username = user.RawData["login"].(string)
u.AvatarUrl = user.AvatarURL
u.AccessToken = user.AccessToken
u.ProfileUrl = user.RawData["url"].(string)
u.Email = user.Email
u.Joined = user.RawData["created_at"].(string)
u.Raw = user.RawData
if u.Id != 0 {
u.UpdateTime()
_, err = dbmap.Update(&u)
if err != nil {
logging.ErrorWithTags([]string{"db"}, "Failed to update user row", err.Error())
}
} else {
err = u.Create()
if err != nil {
logging.ErrorWithTags([]string{"db"}, "Failed to create new user row", err.Error())
}
//Add the user's go routine
StartUserRoutine(u, activityChan)
}
c.JSON(200, u)
}
示例15: sessionsCreate
func sessionsCreate(res http.ResponseWriter, req *http.Request) {
user, err := gothic.CompleteUserAuth(res, req)
if err != nil {
panic(err)
}
currentUser := FindOrCreateUserFromAuthHash(user)
encriptKey := os.Getenv("ENCRIPT_KEY")
token := hex.EncodeToString(encrypt(encriptKey, make([]byte, currentUser.Id)))
http.SetCookie(res, &http.Cookie{
Name: "session",
Value: token,
Path: "/",
})
http.Redirect(res, req, "/", http.StatusFound)
}