Пример #1
0
        public async Task <Message <string> > Register(RegisterBindingModel model)
        {
            using (costmanagerdbEntities db = new costmanagerdbEntities())
            {
                var userExists = db.Users.Any(x => x.Login == model.Login);
                if (userExists)
                {
                    return new Message <string> {
                               StatusCode = (int)HttpStatusCode.Conflict, ReturnMessage = "Change username", IsSuccess = false
                    }
                }
                ;
                else
                {
                    db.Users.Add(new Models.Db.User {
                        Login = model.Login, Password = model.Password
                    });

                    await db.SaveChangesAsync();

                    var user = new ApplicationUser()
                    {
                        UserName = model.Login, Email = model.Login
                    };
                    IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                    return(new Message <string> {
                        StatusCode = (int)HttpStatusCode.OK, ReturnMessage = "Registered", IsSuccess = true
                    });
                }
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (costmanagerdbEntities db = new costmanagerdbEntities())
            {
                var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

                ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);


                var userDb = db.Users.Where(x => x.Login == context.UserName && x.Password == context.Password).FirstOrDefault();
                if (userDb == null || user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                    OAuthDefaults.AuthenticationType);

                oAuthIdentity.AddClaim(new Claim(Consts.useDbId, userDb.ID.ToString()));
                ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                      CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = CreateProperties(user.UserName);
                AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }