當前位置: 首頁>>代碼示例>>Golang>>正文


Golang User.Auth方法代碼示例

本文整理匯總了Golang中rter/data.User.Auth方法的典型用法代碼示例。如果您正苦於以下問題:Golang User.Auth方法的具體用法?Golang User.Auth怎麽用?Golang User.Auth使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在rter/data.User的用法示例。


在下文中一共展示了User.Auth方法的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: AuthHandlerFunc

// Handle requests containing JSON with user credentials. If the credentials are valid the response will set a session cookie effectively logging in the user.
//
// Expected JSON format:
// 	{"Username":"theusername", "Password":"userpassword"}
//
// Invalid credentials will result in a 401 StatusUnauthorized response. Malformed JSON will result in a 400 StatusBadRequest or possibly 500 StatusInternalServerError.
func AuthHandlerFunc(w http.ResponseWriter, r *http.Request) {
	// Parse the JSON into a user object
	loginInfo := new(data.User)

	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&loginInfo)

	if err != nil {
		log.Println("JSON problem")
		log.Println(err)
		http.Error(w, "Malformed json.", http.StatusBadRequest)
		return
	}

	// Try and load the actual user
	user := new(data.User)
	user.Username = loginInfo.Username

	err = storage.Select(user)

	if err == storage.ErrZeroAffected {
		log.Println("No such user: ", user.Username)
		http.Error(w, "Invalid credentials.", http.StatusUnauthorized)
		return
	} else if err != nil {
		log.Println(err)
		http.Error(w, "Database error, likely due to malformed request.", http.StatusInternalServerError)
		return
	}

	// Validate
	if !user.Auth(loginInfo.Password) {
		log.Println("Wrong Password for: ", user.Username)
		http.Error(w, "Invalid credentials.", http.StatusUnauthorized)
		return
	}

	// Get role permissions
	role := new(data.Role)
	role.Title = user.Role

	err = storage.Select(role)

	if err != nil {
		log.Println("Issues loading role during auth", err)
		role.Permissions = 0 // Default to no permissions
	}

	// Build a cookie session
	session, _ := store.Get(r, "rter-credentials")

	session.Values["username"] = user.Username
	session.Values["role"] = user.Role
	session.Values["permissions"] = role.Permissions

	err = session.Save(r, w)

	if err != nil {
		log.Println(err)
	}
}
開發者ID:falahhaprak,項目名稱:rter,代碼行數:67,代碼來源:auth.go


注:本文中的rter/data.User.Auth方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。