// Returns the current user requesting the page func getUser(w http.ResponseWriter, r *http.Request, ctx context.Context) stackongo.User { guest := stackongo.User{ Display_name: "Guest", } // Collect userId from browser cookie username, err := r.Cookie("user_name") if err == nil && username.Value != "" && username.Value != "Guest" { user := readUserFromDb(ctx, username.Value) updateLoginTime(ctx, user.User_id) return user } // If user_id cookie is not set, look for code in url request to collect access token. // If code is not available, return guest user code := r.FormValue("code") if code == "" { log.Infof(ctx, "Returning guest user") guest.User_type = "no_code" return guest } queries := r.URL.Query() queries.Del("code") r.URL.RawQuery = queries.Encode() // Collect access token using the recieved code access_tokens, err := backend.ObtainAccessToken(code, r.URL.String()) if err != nil { log.Warningf(ctx, "Access token not obtained: %v", err.Error()) guest.User_type = "no_access_token" return guest } // Get the authenticated user with the collected access token user, err := backend.AuthenticatedUser(map[string]string{}, access_tokens["access_token"]) if err != nil { log.Warningf(ctx, "User not authenticated: %v", err) guest.User_type = "not_on_SO" return guest } // Add user to db if not already in addUserToDB(ctx, user) //zhu li do the thing updateLoginTime(ctx, user.User_id) return user }
func getUser(w http.ResponseWriter, r *http.Request, c appengine.Context) stackongo.User { // Collect access token from browswer cookie // If cookie does not exist, obtain token using code from URL and set as cookie // If code does not exist, redirect to login page for authorization cookie, err := r.Cookie("access_token") var token string if err != nil { code := r.URL.Query().Get("code") if code == "" { c.Infof("Returning Guest user") return guest } access_tokens, err := backend.ObtainAccessToken(code) if err != nil { c.Errorf(err.Error()) return guest } c.Infof("Setting cookie: access_token") token = access_tokens["access_token"] http.SetCookie(w, &http.Cookie{Name: "access_token", Value: token}) } else { token = cookie.Value } user, err := backend.AuthenticatedUser(map[string]string{}, token) if err != nil { c.Errorf(err.Error()) return guest } data.CacheLock.Lock() if _, ok := data.Users[user.User_id]; !ok { data.Users[user.User_id] = newUser(user, token) addUserToDB(user) } data.CacheLock.Unlock() return user }