示例#1
0
文件: auth.go 项目: surma/importalias
func BasicAuth(umgr UserManager) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		authhdr := r.Header.Get("Authorization")
		if len(authhdr) == 0 {
			return
		}
		authhdrs := strings.Fields(authhdr)
		if len(authhdrs) != 2 || authhdrs[0] != "Basic" {
			http.NotFound(w, r)
			return
		}
		credential, err := base64.URLEncoding.DecodeString(authhdrs[1])
		if err != nil {
			http.NotFound(w, r)
			return
		}
		credentials := strings.Split(string(credential), ":")
		if len(credentials) != 2 {
			http.NotFound(w, r)
			return
		}
		apikey, err := gouuid.ParseString(credentials[0])
		if err != nil {
			http.NotFound(w, r)
			return
		}
		user, err := umgr.FindByAPIKey(&apikey)
		if err != nil {
			http.NotFound(w, r)
			return
		}
		context.Set(r, "uid", user.UID)
	})
}
示例#2
0
文件: auth.go 项目: surma/importalias
func SessionHandler(s sessions.Store, ttl int) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		session, err := s.Get(r, "session")
		if err != nil {
			session.Values = make(map[interface{}]interface{})
		}
		if uid, ok := session.Values["uid"]; ok {
			context.Set(r, "uid", uid)
		}
		session.Options.MaxAge = ttl
		context.Set(r, "session", session)
		if err := session.Save(r, w); err != nil {
			http.Error(w, fmt.Sprintf("Could not save session: %s", err), http.StatusInternalServerError)
		}
	})
}