示例#1
0
文件: controller.go 项目: Kaign/juno
func (c Controller) dbErrOrEmpty(w http.ResponseWriter, err error, msg string) bool {
	if c.stg.IsErrNotFound(err) {
		io.Err(w, msg, http.StatusNotFound)
		return true
	}
	return check.DBErr(w, err)
}
示例#2
0
文件: controller.go 项目: Kaign/juno
func (c Controller) UserCreate(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	user := &model.User{}
	if check.InputErr(w, r, user) {
		return
	}

	// Validate says which field is invalid
	if msg := user.Validate(); msg != "" {
		io.ErrClient(w, msg)
		return
	}

	// we check dublicates on insert
	user, err := c.stg.UserInsert(ctx, user)
	if err != nil {
		if c.stg.IsErrDup(err) {
			io.ErrClient(w, "The email is already registered")
			return
		}
		check.DBErr(w, err)
		return
	}

	// success
	resp := map[string]string{
		"message": "Please, check your mailbox for confirmation letter",
		"id":      user.ID,
	}
	io.Output(w, resp)
}
示例#3
0
文件: controller.go 项目: Kaign/juno
func (c Controller) ProfileAll(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	profiles, err := c.stg.ProfileSearch(ctx, nil)
	if check.DBErr(w, err) {
		return
	}

	io.Output(w, profiles)
}
示例#4
0
// Handle add authorization check middleware before handler call.
// It stores auth info in context
func (mw authMW) Handle(method, path string, handler JunoHandler) {
	authHandler := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		const basicPrefix string = "Basic "

		// Get the Basic Authentication credentials
		auth := r.Header.Get("Authorization")
		if strings.HasPrefix(auth, basicPrefix) {
			// Check credentials
			payload, err := base64.StdEncoding.DecodeString(auth[len(basicPrefix):])
			if err == nil {
				pair := bytes.SplitN(payload, []byte(":"), 2)
				if len(pair) == 2 {
					// look for user in storage.
					filter := model.Fields{"email": string(pair[0]), "password": string(pair[1])}
					user, err := mw.stg.UserSearch(ctx, filter)

					if mw.stg.IsErrNotFound(err) {
						io.Err(w, io.ERR_FORBIDDEN, http.StatusForbidden)
						return
					}
					if check.DBErr(w, err) {
						return
					}

					// put user to context
					ctx = model.SetCtxUser(ctx, user)

					// Delegate request to the given handle
					handler(ctx, w, r)
					return
				}
			}
		}

		// Request Basic Authentication otherwise
		w.Header().Set("WWW-Authenticate", "Basic realm=\"Private Area\"")
		io.Err(w, io.ERR_UNAUTHORIZED, http.StatusUnauthorized)
	}

	// configure base router with auth handler
	mw.base.Handle(method, path, JunoHandler(authHandler))
}