Beispiel #1
0
        public async Task <_IdentityData> LoginExternalAsync(string providerName, string providerKey)
        {
            _IdentityData data = null;

            try
            {
                UserLoginInfo loginInfo = new UserLoginInfo(providerName, providerKey);

                Account account = await _accountService.FindAsyncExternal(loginInfo);

                if (account != null)
                {
                    data = new _IdentityData()
                    {
                        Data = account
                    };
                }
            }
            catch (Exception ex)
            {
                _loggingService.Write(GetType().Name, nameof(LoginExternalAsync), ex);
            }

            return(data);
        }
Beispiel #2
0
        public async Task <_IdentityData> Find(string username, string password)
        {
            _IdentityData identityData = null;

            try
            {
                identityData = new _IdentityData();

                Account account = await _accountService.FindAsync(username ?? string.Empty, password ?? string.Empty);

                if (account == null)
                {
                    identityData.Errors.Add("Invalid username or password");
                }
                if (account.LockoutEnabled)
                {
                    identityData.Errors.Add("Bannded");
                }
                else
                {
                    ClaimsIdentity claims = await _accountService
                                            .CreateIdentityAsync(account, DefaultAuthenticationTypes.ApplicationCookie);

                    identityData.Data = claims;
                }// end if check is login successful
            }
            catch (Exception ex)
            {
                _loggingService.Write(GetType().Name, nameof(Find), ex);
            }

            return(identityData);
        }
        //[OverrideAuthentication]
        //[HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
        //[AllowAnonymous]
        //[Route("ExternalLogin", Name = "ExternalLogin")]
        //public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
        //{
        //    string redirectUri = string.Empty;

        //    if (error != null)
        //    {
        //        return BadRequest(Uri.EscapeDataString(error));
        //    }

        //    if (!User.Identity.IsAuthenticated)
        //    {
        //        return new _ExternalOAuthServer(provider, this.Request);
        //    }

        //    var redirectUriValidationResult = ValidateClientAndRedirectUri(this.Request, ref redirectUri);

        //    if (!string.IsNullOrWhiteSpace(redirectUriValidationResult))
        //    {
        //        return BadRequest(redirectUriValidationResult);
        //    }

        //    ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

        //    if (externalLogin == null)
        //    {
        //        return InternalServerError();
        //    }

        //    if (externalLogin.LoginProvider != provider)
        //    {
        //        Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        //        return new _ExternalOAuthServer(provider, this.Request);
        //    }

        //    var user = await _identityService.LoginExternalAsync(externalLogin.LoginProvider, externalLogin.ProviderKey);

        //    bool hasRegistered = user != null;

        //    redirectUri = string.Format("{0}#external_access_token={1}&provider={2}&haslocalaccount={3}&external_user_name={4}",
        //                                    redirectUri,
        //                                    externalLogin.ExternalAccessToken,
        //                                    externalLogin.LoginProvider,
        //                                    hasRegistered.ToString(),
        //                                    externalLogin.UserName);

        //    return Redirect(redirectUri);

        //}
        public async Task <IHttpActionResult> Register(RegisterViewModels register)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _IdentityData result = await _identityService.Create(register.EmailAddress, register.Password,
                                                                         register.FullName, register.Address, register.PhoneNumber,
                                                                         register.Birthdate, nameof(RoleType.User));

                    if (result.IsError)
                    {
                        base.AddModelError(result.Errors[0]);

                        return(BadRequest(ModelState));
                    }
                    else
                    {
                        return(Ok());
                    }//end if check is existed errors
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception ex)
            {
                _loggingService.Write(GetType().Name, nameof(Register), ex);

                return(InternalServerError(ex));
            }
        }
Beispiel #4
0
        public async Task <_IdentityData> FindAsync(string provider, string userId)
        {
            _IdentityData data = new _IdentityData();

            data.Data = await _accountService.FindAsync(new UserLoginInfo(provider, userId)) as Account;

            return(data);
        }
Beispiel #5
0
        public async Task <_IdentityData> AddLoginAsync(string userId, string a, string b)
        {
            try
            {
                UserLoginInfo  login      = new UserLoginInfo(a, b);
                _IdentityData  result     = new _IdentityData();
                IdentityResult reuslttest = await _accountService.AddLoginAsync(userId, login);

                result.Data = reuslttest;
                return(result);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #6
0
        public async Task <_IdentityData> FindByUsername(string username)
        {
            _IdentityData identityData = null;

            try
            {
                identityData = new _IdentityData();

                Account account = await _accountService.FindAsync(username ?? string.Empty, "abcdefghijklmnopqrstuvwxyz");

                identityData.Data = account;
                return(identityData);
            }
            catch (Exception ex)
            {
                _loggingService.Write(GetType().Name, nameof(Find), ex);
            }

            return(identityData);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

            if (allowedOrigin == null)
            {
                allowedOrigin = "*";
            }


            if (!context.Response.Headers.Keys.Contains("Access-Control-Allow-Origin"))
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
            }
            else
            {
                context.Response.Headers.Set("Access-Control-Allow-Origin", $"{allowedOrigin}");
            }//cors


            _IdentityData data = await _identityService.Find(context.UserName, context.Password);

            if (data.IsError)
            {
                context.SetError("invalid_grant", data.Errors[0]);
            }
            else
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);

                var props = new AuthenticationProperties(
                    new Dictionary <string, string>
                {
                    { "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId },
                    { "userName", context.UserName },
                    { "role", await _identityService.GetRole(context.UserName) }
                });
                context.Validated(new AuthenticationTicket(data.Data as ClaimsIdentity, props));
            }//end if check is error
        }
        public async Task <IHttpActionResult> Register(RegisterViewModels register)
        {
            try
            {
                var year = UserController.DateDiffYears(register.Birthdate, DateTimeOffset.Now);
                if (year <= 10)
                {
                    ModelState.AddModelError(string.Empty, "Ngày sinh phải cách hiện tại 10 năm");
                }
                if (ModelState.IsValid)
                {
                    _IdentityData result = await _identityService.Create(register.EmailAddress, register.Password,
                                                                         register.FullName, register.Address, register.PhoneNumber,
                                                                         register.Birthdate, nameof(RoleType.User));

                    if (result.IsError)
                    {
                        base.AddModelError(result.Errors[0]);

                        return(BadRequest(ModelState));
                    }
                    else
                    {
                        return(Ok());
                    }//end if check is existed errors
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception ex)
            {
                _loggingService.Write(GetType().Name, nameof(Register), ex);

                return(InternalServerError(ex));
            }
        }
Beispiel #9
0
        public async Task <_IdentityData> Create(string usernameOrEmail, string password, string fullName,
                                                 string address, string phoneNumber, DateTimeOffset birthdate, params string[] roles)
        {
            _IdentityData identityData = null;

            try
            {
                using (TransactionScope scope = new TransactionScope
                                                    (TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
                {
                    identityData = new _IdentityData();
                    User user = null;
                    //create user extenstion data
                    user = new Creator
                    {
                        FullName  = fullName,
                        Birthdate = birthdate,
                    };

                    int userId = _userService.CreateUser(user);
                    //create account

                    Account account = new Account
                    {
                        UserName = usernameOrEmail,
                        UserId   = userId,
                        Email    = usernameOrEmail,
                    };
                    IdentityResult result = await _accountService.CreateAsync(account, password);

                    if (!result.Succeeded)
                    {
                        identityData.Errors.AddRange(result.Errors);
                    }
                    else
                    {
                        bool isAdd = false;
                        foreach (string roleName in roles)
                        {
                            isAdd = true;
                            if (!await _roleService.RoleExistsAsync(roleName))
                            {
                                result = await _roleService.CreateAsync(new Role { Name = roleName });

                                if (!result.Succeeded)
                                {
                                    identityData.Errors.AddRange(result.Errors);
                                }
                            }

                            if (!await _accountService.IsInRoleAsync(account.Id, roleName))
                            {
                                result = await _accountService.AddToRolesAsync(account.Id, roleName);

                                if (!result.Succeeded)
                                {
                                    identityData.Errors.AddRange(result.Errors);
                                }
                            } //check is user existed in role
                        }     //crawl roles collection
                        if (!isAdd)
                        {
                            await _accountService.AddToRoleAsync(account.Id, "User");
                        }
                    }//is create account successful
                    if (!identityData.IsError)
                    {
                        scope.Complete();
                    } //check is error
                }     //end scope
            }
            catch (Exception ex)
            {
                _loggingService.Write(GetType().Name, nameof(Create), ex);
            }

            return(identityData);
        }