Exemplo n.º 1
0
        public async Task <IHttpActionResult> ProcessExternalLogin()
        {
            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

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

            var user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (!hasRegistered)
            {
                //зарегестрировать и авторизировать пользователя
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);

                var userInfo = UserManager2.CreateUserInfo("", externalLogin.UserName, "", "", "");

                user = new User()
                {
                    UserName      = externalLogin.UserName,
                    PasswordHash  = null,
                    IsActive      = true,
                    UserType      = (int)UserTypeEnum.Client,
                    UserInfoId    = userInfo.Id,
                    AccountPlanId = (int)AccountPlanEnum.Start,
                    Registration  = DateTime.Now,
                    LastUpdate    = DateTime.Now
                };

                IdentityResult result = await UserManager.CreateAsync(user);

                IdentityResult loginResult = await UserManager.AddLoginAsync(user.Id, new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

                //SignInManager.SignIn(user, false, false);
                //Authentication.SignIn(identity);
            }

            //авторизировать пользователя
            SignInManager.SignOut();
            //Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

            ClaimsIdentity oAuthIdentity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await UserManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);

            SignInManager.SignIn(user, false, false);
            //Authentication.SignIn(properties, oAuthIdentity, cookiesIdentity);

            return(Ok());
        }
Exemplo n.º 2
0
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

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

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

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

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

            var user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                SignInManager.SignOut();
                //Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookiesIdentity = await UserManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                SignInManager.SignIn(user, false, false);
                //Authentication.SignIn(properties, oAuthIdentity, cookiesIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);

                var userInfo = UserManager2.CreateUserInfo("", externalLogin.UserName, "", "", "");

                user = new User()
                {
                    UserName      = externalLogin.UserName,
                    PasswordHash  = null,
                    IsActive      = true,
                    UserType      = (int)UserTypeEnum.Client,
                    UserInfoId    = userInfo.Id,
                    AccountPlanId = (int)AccountPlanEnum.Start,
                    Registration  = DateTime.Now,
                    LastUpdate    = DateTime.Now
                };

                IdentityResult result = await UserManager.CreateAsync(user);

                IdentityResult loginResult = await UserManager.AddLoginAsync(user.Id, new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey));

                SignInManager.SignIn(user, false, false);
                //Authentication.SignIn(identity);
            }

            return(Ok());
        }
Exemplo n.º 3
0
        public async Task <object> Register()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            byte[] buffer = null;
            string filename;
            string email           = string.Empty;
            string username        = string.Empty;
            string password        = string.Empty;
            string confirmpassword = string.Empty;

            var fileManager = new AzureFileManager();

            foreach (var file in provider.Contents)
            {
                if (file.Headers.ContentDisposition.Name.Contains("email"))
                {
                    email = await file.ReadAsStringAsync();
                }
                else if (file.Headers.ContentDisposition.Name.Contains("username"))
                {
                    username = await file.ReadAsStringAsync();
                }
                else if (file.Headers.ContentDisposition.Name.Contains("password"))
                {
                    password = await file.ReadAsStringAsync();
                }
                else if (file.Headers.ContentDisposition.Name.Contains("confirmpassword"))
                {
                    confirmpassword = await file.ReadAsStringAsync();
                }
                else
                {
                    filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                    buffer   = await file.ReadAsByteArrayAsync();
                }
            }

            var model = new RegisterBindingModel()
            {
                email           = email,
                username        = username,
                password        = password,
                confirmpassword = confirmpassword,
            };

            logger.Log(LogLevel.Info, $"Register({model.email})");
            if (!ModelState.IsValid)
            {
                logger.Log(LogLevel.Error, $"Register({model.email}). Error: model state is not invalid");
                return(BadRequest(ModelState));
            }

            //var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
            var userInfo = UserManager2.CreateUserInfo("", username, "", "", "");

            var user = new User()
            {
                UserName      = model.email,
                PasswordHash  = model.password,
                IsActive      = true,
                UserInfoId    = userInfo.Id,
                UserType      = (int)UserTypeEnum.Client,
                AccountPlanId = (int)AccountPlanEnum.Start,
                Registration  = DateTime.Now,
                LastUpdate    = DateTime.Now
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }
            user = UserManager2.Create(user);
            //SignInManager.SignIn(user, false, false);
            ClaimsIdentity oAuthIdentity = await UserManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await UserManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);

            Authentication.SignIn(properties, oAuthIdentity, cookiesIdentity);

            var token = GetToken(model.email, model.password);

            //avatar
            var uploadResult = fileManager.UploadFileAsync(buffer, $"{user.Id}.png");//pass file stream

            if (string.IsNullOrEmpty(uploadResult.Result))
            {
                return(BadRequest(uploadResult.Result));
            }


            var info = UserManager2.FindUserInfo(user.UserInfoId);

            info.PhotoUrl = uploadResult.Result;
            UserManager2.UpdateInfo(info);
            try
            {
                GroupManager.CreateFavorites(user.Id);
            }
            catch (Exception ex)
            { }

            var usermodel = UserManager2.GetUserModel(user.UserName);

            return(new
            {
                token = token,
                user = usermodel
            });
        }