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


Golang go-appkit.User類代碼示例

本文整理匯總了Golang中github.com/app-kit/go-appkit.User的典型用法代碼示例。如果您正苦於以下問題:Golang User類的具體用法?Golang User怎麽用?Golang User使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


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

示例1: SetUser

func (m *StrUserModel) SetUser(u kit.User) {
	if u == nil {
		m.User = nil
		m.UserId = ""
	} else {
		m.User = u.(*UserStrId)
		m.SetUserId(u.GetId())
	}
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:9,代碼來源:models.go

示例2: ApiCreate

// Creating a session is equivalent to logging in.
func (hooks SessionResourceHooks) ApiCreate(res kit.Resource, obj kit.Model, r kit.Request) kit.Response {
	userService := res.Registry().UserService()

	meta := r.GetMeta()

	isAnonymous, _ := meta.Bool("anonymous")

	// Find user.
	userIdentifier := meta.String("user")
	adaptor := meta.String("adaptor")
	data, _ := meta.Map("authData")

	var user kit.User
	if !isAnonymous {
		if adaptor == "" {
			return kit.NewErrorResponse("adaptor_missing", "Expected 'adaptor' in metadata.", true)
		}

		if data == nil {
			kit.NewErrorResponse("no_or_invalid_auth_data", "Expected 'authData' dictionary in metadata.")
		}

		var err apperror.Error
		user, err = userService.AuthenticateUser(userIdentifier, adaptor, data)
		if err != nil {
			return kit.NewErrorResponse(err)
		}
	}

	session, err := userService.StartSession(user, r.GetFrontend())
	if err != nil {
		return kit.NewErrorResponse(err)
	}

	responseMeta := make(map[string]interface{})

	if !isAnonymous {
		userData, err := res.Backend().ModelToMap(user, true, false)
		if err != nil {
			return kit.NewErrorResponse("marshal_error", err)
		}
		responseMeta["user"] = userData

		if user.GetProfile() != nil {
			profileData, err := res.Backend().ModelToMap(user.GetProfile(), true, false)
			if err != nil {
				return kit.NewErrorResponse("marshal_error", err)
			}
			responseMeta["profile"] = profileData
		}
	}

	return &kit.AppResponse{
		Data: session,
		Meta: responseMeta,
	}
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:58,代碼來源:resources.go

示例3: AllowFind

func (UserResource) AllowFind(res kit.Resource, model kit.Model, user kit.User) bool {
	if user == nil {
		return false
	}
	if model.(kit.UserModel).GetUserId() == user.GetId() {
		return true
	}
	return user.HasRole("admin")
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:9,代碼來源:resource.go

示例4: AuthenticateUser

func (h *Service) AuthenticateUser(userIdentifier string, authAdaptorName string, data map[string]interface{}) (kit.User, apperror.Error) {
	authAdaptor := h.AuthAdaptor(authAdaptorName)
	if authAdaptor == nil {
		return nil, &apperror.Err{
			Public:  true,
			Code:    "unknown_auth_adaptor",
			Message: "Unknown auth adaptor: " + authAdaptorName}
	}

	var user kit.User
	var err apperror.Error

	if userIdentifier != "" {
		user, err = h.FindUser(userIdentifier)

		if err != nil {
			return nil, err
		} else if user == nil {
			return nil, apperror.New("user_not_found", "Username/Email does not exist ", true)
		}
	}

	userId := ""
	if user != nil {
		userId = user.GetStrId()
	}

	userId, err = authAdaptor.Authenticate(userId, data)
	if err != nil {
		if err.IsPublic() {
			return nil, err
		} else {
			return nil, apperror.Wrap(err, "adaptor_error", true)
		}
	}

	if user == nil {
		// Query user to get a full user with permissions and profile.
		user, err = h.FindUser(userId)
		if err != nil {
			return nil, err
		} else if user == nil {
			return nil, &apperror.Err{
				Code:    "user_not_found",
				Message: fmt.Sprintf("User with id %v could not be found", userId),
				Public:  true,
			}
		}
	}

	if !user.IsActive() {
		return nil, apperror.New("user_inactive", true)
	}

	return user, nil
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:56,代碼來源:service.go

示例5: AllowFind

func (PageResource) AllowFind(res kit.Resource, obj kit.Model, user kit.User) bool {
	if p, ok := obj.(*PageIntId); ok && p.Published {
		return true
	} else if p, ok := obj.(*PageStrId); ok && p.Published {
		return true
	}

	u := obj.(kit.UserModel)

	return user != nil && (u.GetUserId() == user.GetId() || user.HasRole("admin"))
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:11,代碼來源:resources.go

示例6: RegisterUser

func (a *AuthAdaptorPassword) RegisterUser(user kit.User, data map[string]interface{}) (kit.AuthItem, apperror.Error) {
	if data == nil {
		return nil, apperror.New("invalid_nil_data")
	}
	pw, _ := GetStringFromMap(data, "password")
	if pw == "" {
		return nil, apperror.New("invalid_data_no_password")
	}

	hash, err := bcrypt.GenerateFromPassword([]byte(pw), 10)
	if err != nil {
		return nil, apperror.Wrap(err, "hash_errr", "")
	}

	item := &AuthItemPassword{
		Hash: string(hash),
	}
	item.SetId(user.GetId())

	return item, nil
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:21,代碼來源:password.go

示例7: ChangePassword

func (s *Service) ChangePassword(user kit.User, newPassword string) apperror.Error {
	adaptor := s.AuthAdaptor("password")
	if adaptor == nil {
		return &apperror.Err{
			Code:    "no_password_adaptor",
			Message: "The UserService does not have the password auth adaptor",
		}
	}

	passwordAdaptor := adaptor.(*password.AuthAdaptorPassword)

	if err := passwordAdaptor.ChangePassword(user.GetStrId(), newPassword); err != nil {
		if err.IsPublic() {
			return err
		} else {
			return apperror.Wrap(err, "adapter_error")
		}
		return err
	}

	return nil
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:22,代碼來源:service.go

示例8: AllowUpdate

func (hooks UserResourceHooks) AllowUpdate(res kit.Resource, obj kit.Model, old kit.Model, user kit.User) bool {
	if user == nil {
		return false
	}
	if user.HasRole("admin") || user.HasPermission("users.update") {
		return true
	}
	return obj.GetId() == user.GetId()
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:9,代碼來源:resources.go

示例9: AllowDelete

func (UserResource) AllowDelete(res kit.Resource, obj kit.Model, user kit.User) bool {
	if user == nil {
		return false
	}
	if obj.(kit.UserModel).GetUserId() == user.GetId() {
		return true
	}
	return user.HasRole("admin") || user.HasPermission(res.Collection()+".delete")
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:9,代碼來源:resource.go

示例10: Create

func (res *Resource) Create(obj kit.Model, user kit.User) apperror.Error {
	if hook, ok := res.hooks.(CreateHook); ok {
		return hook.Create(res, obj, user)
	}

	// This has to be done before tthe AllowCreate hook to allow the hook to
	// compare UserId value.
	if userModel, ok := obj.(kit.UserModel); ok && user != nil {
		if reflector.R(userModel.GetUserId()).IsZero() {
			userModel.SetUserId(user.GetId())
		}
	}

	if allowCreate, ok := res.hooks.(AllowCreateHook); ok {
		if !allowCreate.AllowCreate(res, obj, user) {
			return apperror.New("permission_denied")
		}
	}

	if beforeCreate, ok := res.hooks.(BeforeCreateHook); ok {
		if err := beforeCreate.BeforeCreate(res, obj, user); err != nil {
			return err
		}
	}

	if err := res.backend.Create(obj); err != nil {
		return err
	}

	if afterCreate, ok := res.hooks.(AfterCreateHook); ok {
		if err := afterCreate.AfterCreate(res, obj, user); err != nil {
			return err
		}
	}

	return nil
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:37,代碼來源:resource.go

示例11: StartSession

func (s Service) StartSession(user kit.User, sessionType string) (kit.Session, apperror.Error) {
	token := randomToken()
	if token == "" {
		return nil, apperror.New("token_creation_failed")
	}

	session := s.Sessions.CreateModel().(kit.Session)

	session.SetType(sessionType)
	session.SetToken(token)
	session.SetStartedAt(time.Now())
	session.SetValidUntil(time.Now().Add(time.Hour * 12))

	if user != nil {
		session.SetUserId(user.GetId())
	}

	err := s.Sessions.Create(session, nil)
	if err != nil {
		return nil, err
	}

	return session, nil
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:24,代碼來源:service.go

示例12: VerifySession

func (h *Service) VerifySession(token string) (kit.User, kit.Session, apperror.Error) {
	rawSession, err := h.Sessions.FindOne(token)
	if err != nil {
		return nil, nil, err
	} else if rawSession == nil {
		return nil, nil, apperror.New("session_not_found", true)
	}
	session := rawSession.(kit.Session)

	if session.GetValidUntil().Sub(time.Now()) < 1 {
		return nil, nil, apperror.New("session_expired", true)
	}

	var user kit.User

	if !session.IsAnonymous() {
		// Load user.
		rawUser, err := h.FindUser(session.GetUserId())
		if err != nil {
			return nil, nil, err
		}
		user = rawUser.(kit.User)

		if !user.IsActive() {
			return nil, nil, apperror.New("user_inactive", true)
		}
	}

	// Prolong session.
	session.SetValidUntil(time.Now().Add(time.Hour * 12))
	if err := h.Sessions.Update(session, nil); err != nil {
		return nil, nil, err
	}

	return user, session, nil
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:36,代碼來源:service.go

示例13: SetUser

func (item *AuthItemOauth) SetUser(u kit.User) {
	item.SetUserId(u.GetId())
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:3,代碼來源:oauth.go

示例14: SendPasswordResetEmail

func (s *Service) SendPasswordResetEmail(user kit.User) apperror.Error {
	// Check that an email service is configured.

	mailService := s.registry.EmailService()
	if mailService == nil {
		return apperror.New("no_email_service")
	}

	hoursValid := 48

	// Generate a token.
	expiresAt := time.Now().Add(time.Hour * time.Duration(hoursValid))
	tokenItem, err := s.BuildToken("password_reset", user.GetStrId(), expiresAt)
	if err != nil {
		return err
	}
	token := tokenItem.GetToken()

	conf := s.registry.Config()

	// Build the confirmation url.

	url := conf.UString("url")
	if url == "" {
		return &apperror.Err{
			Code:    "no_url_set",
			Message: "Config must specify url",
		}
	}

	resetPath := conf.UString("users.passwordResetPath")
	if resetPath == "" {
		return &apperror.Err{
			Code:    "no_password_reset_path",
			Message: "Config must specify users.passwordResetPath",
		}
	}

	if !strings.Contains(resetPath, "{token}") {
		return &apperror.Err{
			Code:    "invalid_password_reset_path",
			Message: "users.passwordResetPath does not contain {token} placeholder",
		}
	}
	resetUrl := url + "/" + strings.Replace(resetPath, "{token}", token, -1)

	// Render email.

	subject := conf.UString("users.passwordResetSubject", "Password reset")

	var txtContent, htmlContent []byte

	txtTpl := conf.UString("users.passwordResetTextTpl")
	htmlTpl := conf.UString("users.passwordResetHtmlTpl")
	if txtTpl != "" && htmlTpl != "" {
		// Check that a template engine is configured.
		engine := s.registry.TemplateEngine()
		if engine == nil {
			return apperror.New("no_template_engine")
		}

		data := map[string]interface{}{
			"user":        user,
			"token":       token,
			"hours_valid": hoursValid,
		}
		var err apperror.Error

		txtContent, err = s.registry.TemplateEngine().BuildFileAndRender(txtTpl, data)
		if err != nil {
			return apperror.Wrap(err, "password_reset_tpl_error", "Could not render password reset tpl")
		}

		htmlContent, err = s.registry.TemplateEngine().BuildFileAndRender(htmlTpl, data)
		if err != nil {
			return apperror.Wrap(err, "password_reset_tpl_error", "Could not render password reset tpl")
		}
	} else {
		tpl := `Password reset

To reset your password, please visit %v.
The link will be valid for %v hours.
`

		htmlTpl := `Password Reset<br><br>

To reset your password, please visit <a href="%v">this link</a>.<br>
The link will be valid for %v hours.
`
		txtContent = []byte(fmt.Sprintf(tpl, resetUrl, hoursValid))
		htmlContent = []byte(fmt.Sprintf(htmlTpl, resetUrl, hoursValid))
	}

	// Now build the email and send it.
	email := email.NewMail()
	email.SetSubject(subject)
	email.AddBody("text/plain", txtContent)
	email.AddBody("text/html", htmlContent)
	email.AddTo(user.GetEmail(), "")

//.........這裏部分代碼省略.........
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:101,代碼來源:service.go

示例15: SetUser

func (item *AuthItemPassword) SetUser(u kit.User) {
	item.SetUserId(u.GetId())
}
開發者ID:app-kit,項目名稱:go-appkit,代碼行數:3,代碼來源:password.go


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