Exemple #1
0
        private async Task <ClaimsIdentity> GetClaimsIdentity(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                return(await Task.FromResult <ClaimsIdentity>(null));
            }

            // get the user to verifty
            var user = _context.Users.Where(o => o.username == userName).FirstOrDefault();

            if (user == null)
            {
                return(await Task.FromResult <ClaimsIdentity>(null));
            }

            // check the credentials
            if (user.password == password)
            {
                return(await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(userName, user.id.ToString())));
            }

            // Credentials are invalid, or account doesn't exist
            return(await Task.FromResult <ClaimsIdentity>(null));
        }
Exemple #2
0
        private async Task <ClaimsIdentity> GetClaimsIdentity(string login, string password)
        {
            if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(password))
            {
                return(await Task.FromResult <ClaimsIdentity>(null));
            }

            var passwordHash = VentCalc.Models.User.GenerateMd5Hash(password);
            var userToVerify = await _unitOfWork.Repository <User>()
                               .GetSingleIcludeMultipleAsync(x => x.Login == login &&
                                                             x.Password == passwordHash);

            if (userToVerify == null)
            {
                return(await Task.FromResult <ClaimsIdentity>(null));
            }

            if (CheckPasswordAsync(userToVerify, passwordHash))
            {
                return(await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(login, userToVerify.Id.ToString())));
            }

            return(await Task.FromResult <ClaimsIdentity>(null));
        }
Exemple #3
0
        private async Task <ClaimsIdentity> GetClaimsIdentity(string email, string password)
        {
            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
            {
                return(null);
            }

            // get the user to verifty
            var userToVerify = await _userManager.FindByEmailAsync(email);

            if (userToVerify == null)
            {
                return(null);
            }

            // check the credentials
            if (await _userManager.CheckPasswordAsync(userToVerify, password))
            {
                return(await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(userToVerify.Email, (await _userManager.GetRolesAsync(userToVerify)).ToArray())));
            }

            // Credentials are invalid, or account doesn't exist
            return(null);
        }
        private async Task <ClaimsIdentity> GetClaimsIdentity(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
            {
                return(await Task.FromResult <ClaimsIdentity>(null));
            }

            // get the user to verifty
            var userToVerify = await _userManager.FindByNameAsync(userName);

            if (userToVerify == null)
            {
                return(await Task.FromResult <ClaimsIdentity>(null));
            }

            // check the credentials
            if (await _userManager.CheckPasswordAsync(userToVerify, password))
            {
                return(await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(userName, userToVerify.Id)));
            }

            // Credentials are invalid, or account doesn't exist
            return(await Task.FromResult <ClaimsIdentity>(null));
        }
Exemple #5
0
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> Login([FromBody] LoginViewModel model)
        {
            if (!this.ValidateRecaptcha(model.Recaptcha))
            {
                return(BadRequest(Errors.AddErrorToModelState("Recaptcha", "Please verify that you are not a robot.", ModelState)));
            }

            if (ModelState.IsValid)
            {
                model.Username = model.Username.ToLowerInvariant();

                // Require the user to have a confirmed email before they can log on.
                var user = await _userManager.FindByNameAsync(model.Username);

                if (user != null)
                {
                    if (!await _userManager.IsEmailConfirmedAsync(user))
                    {
                        ModelState.AddModelError(string.Empty,
                                                 "You must have a confirmed email to sign in.");
                        return(BadRequest(Errors.AddErrorToModelState("Email", "You must have a confirmed email to sign in.", ModelState)));
                    }
                }

                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    HttpContext.User = await _userClaimsPrincipalFactory.CreateAsync(user);

                    var tokens = _antiforgery.GetAndStoreTokens(HttpContext);

                    var identity = _jwtFactory.GenerateClaimsIdentity(model.Username, user.Id);
                    var tenant   = string.Empty;
                    if (_configuration["DomainAsTenant"] == "y")
                    {
                        tenant = user.Tenant;
                        if (string.IsNullOrEmpty(tenant))
                        {
                            tenant = this.GetUserDomain(user.Email);
                        }
                    }

                    var profile = await _contentItemRepository.CreateProfileIfNotExists(
                        tenant,
                        user.Id,
                        user.UserName,
                        user.Email);

                    bool isSuperAdmin = _claimsService.IsSuperAdmin(user.UserName);
                    bool isAdmin      = (_claimsService.IsAdmin(HttpContext.User) || isSuperAdmin);
                    _logger.LogInformation(1, "User logged in.");
                    var jwt = await Tokens.GenerateJwt(
                        identity,
                        _jwtFactory,
                        user.UserName,
                        tenant,
                        user.Email,
                        isAdmin,
                        isSuperAdmin,
                        _jwtOptions,
                        new JsonSerializerSettings { Formatting = Formatting.Indented }
                        );

                    return(new OkObjectResult(jwt));
                }

                if (result.RequiresTwoFactor)
                {
                    //return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                }

                if (result.IsLockedOut)
                {
                    string message = "User account locked out.";
                    _logger.LogWarning(2, message);
                    return(BadRequest(Errors.AddErrorToModelState("Email", message, ModelState)));
                }

                if (result.IsNotAllowed)
                {
                    string message = "User account is not allowed to sign in.";
                    _logger.LogWarning(2, message);
                    return(BadRequest(Errors.AddErrorToModelState("Email", message, ModelState)));
                }

                return(BadRequest(Errors.AddErrorToModelState("", "Sign in failed.", ModelState)));
            }

            // If we got this far, something failed, redisplay form
            return(BadRequest(Errors.AddErrorToModelState("", "", ModelState)));
        }
Exemple #6
0
        public async Task <IActionResult> PostTranposte([FromBody] TransporteVM credentials)
        {
            string nomeCompleto = "", email = "", cel = "", uidNumber = "", celTratada = "";

            try
            {
                var decrypted = Decrypt.DecryptString(credentials.Chave, _configuration["Transporte:Chave"]);
                if (!decrypted.Contains(credentials.Usuario.ToUpper().Substring(0, 3)))
                {
                    return(StatusCode(401, new { Name = "Token Invalido." }));
                }
                decrypted = decrypted.Replace(credentials.Usuario.ToUpper().Substring(0, 3), "");
                DateTime dataTransporte = DateTime.ParseExact(decrypted, "ddMMyyyyHH", null);
                if (dataTransporte < DateTime.UtcNow.AddHours(-1))
                {
                    return(StatusCode(401, new { Name = "Token Expirou." }));
                }
            }
            catch (Exception e)
            {
                return(StatusCode(401, new { Name = "Sem Autorização." }));
            }

            using (var cn = new LdapConnection())
            {
                try
                {
                    cn.Connect(_ldapConfig.FirstOrDefault().Hostname, _ldapConfig.FirstOrDefault().Port);

                    cn.Bind(String.Format("stefanini-dom\\{0}", _ldapConfig.FirstOrDefault().LoginAD), _ldapConfig.FirstOrDefault().Password);

                    var    searchBase = string.Empty;
                    string filterInformacaoUsuario = "(sAMAccountName=" + credentials.Usuario + ")";
                    var    search = cn.Search("DC=stefanini,DC=dom", LdapConnection.SCOPE_SUB, filterInformacaoUsuario, null, false);

                    if (search.hasMore())
                    {
                        var nextEntry = search.next();
                        var user      = nextEntry.getAttributeSet();
                        nomeCompleto = (user.getAttribute("displayName") != null) ? user.getAttribute("displayName").StringValue : "";
                        email        = (user.getAttribute("mail") != null) ? user.getAttribute("mail").StringValue : "";
                        cel          = (user.getAttribute("department") != null) ? user.getAttribute("department").StringValue.Split('|')[0] : "";
                        celTratada   = (user.getAttribute("department") != null) ? TratarCelula(user.getAttribute("department").StringValue.Split('|')[0]) : "";
                        uidNumber    = (user.getAttribute("uidNumber") != null) ? user.getAttribute("uidNumber").StringValue : "";
                    }
                }
                catch (LdapException e)
                {
                    return(StatusCode(401, new { Name = "Sem Autorização." }));
                }
            }

            try
            {
                var celulasVisualizadas = ObterCelulasVisualizadas(credentials.Usuario, Convert.ToInt32(celTratada));

                var identity = _jwtFactory.GenerateClaimsIdentity(credentials.Usuario, nomeCompleto, email, null, cel, uidNumber, celulasVisualizadas, celTratada);
                var jwt      = await Tokens.GenerateJwt(identity, _jwtFactory, credentials.Usuario, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });

                var tokenLogin = await GerarTokenLoginUsuario(credentials.Usuario);

                var tokens = new List <string>();
                tokens.Add(jwt);
                tokens.Add(tokenLogin);
                Console.WriteLine("Login realizado: " + nomeCompleto);
                return(new OkObjectResult(tokens));
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #7
0
 private async Task <ClaimsIdentity> GetClaimsIdentity(string userName, string password)
 {
     return(await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(userName, userName)));
 }
        public async Task <IActionResult> LinkedIn([FromBody] LinkedInAuthViewModel model)
        {
            // 1. Request user data from LinkedIn
            var userInfo = await _userSignInService.GetUserBasicProfileDataAsync(model.AccessToken);

            if (userInfo == null)
            {
                return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid or expired LinkedIn token.", ModelState)));
            }

            // 2. ready to create the local user account (if necessary) and jwt
            var user = await _userManager.FindByNameAsync(userInfo.Email);

            if (user == null)
            {
                var appUser = new ApplicationUser
                {
                    FirstName  = userInfo.FirstName,
                    LastName   = userInfo.LastName,
                    LinkedInId = userInfo.Id,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    PictureUrl = userInfo.PictureUrl
                };

                var result = await _userManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8));

                if (!result.Succeeded)
                {
                    return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState)));
                }

                await _unitOfWork.JwtAuthUsersRepository.SaveLinkedInUserBasicProfileData(
                    appUser.Id,
                    model.AccessToken,
                    userInfo
                    );

                await _unitOfWork.CompleteAsync();
            }
            else
            {
                // If the user has selected LinkedIn SignIn/SignUp and arrives here
                // that means that the user has already registered with local account.
                // Update LinkedInId and PictureUrl in the Db if needed.
                // In case the user registered with local account and now signed
                // in with linkedIn with same email address
                if (this._linkedInDataNeedsUpdate(user, userInfo))
                {
                    user.LinkedInId = userInfo.Id;
                    user.PictureUrl = userInfo.PictureUrl;

                    await _userManager.UpdateAsync(user);
                }
            }

            // Try find the local user again if necessary and generate the jwt for him/her
            var localUser = await _userManager.FindByNameAsync(userInfo.Email);

            if (localUser == null)
            {
                return(BadRequest(Errors.AddErrorToModelState("login_failure", "Failed to create local user account.", ModelState)));
            }

            var jwt = await Tokens.GenerateJwt(_jwtFactory.GenerateClaimsIdentity(localUser.UserName, localUser.Id), _jwtFactory, localUser.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });

            return(new OkObjectResult(jwt));
        }
        public async Task <IActionResult> Facebook([FromBody] FacebookAuthViewModel model)
        {
            // 1.generate an app access token
            var appAccessTokenResponse = await Client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={base.AppSettings.FacebookAuthSettings.AppId}&client_secret={base.AppSettings.FacebookAuthSettings.AppSecret}&grant_type=client_credentials");

            var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse);
            // 2. validate the user access token
            var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={model.AccessToken}&access_token={appAccessToken.AccessToken}");

            var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse);

            if (!userAccessTokenValidation.Data.IsValid)
            {
                return(new BadRequestObjectResult(new { error = "Invalid facebook token." }));
            }

            // 3. we've got a valid token so we can request user data from fb
            var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v3.0/me?fields=id,email,first_name,last_name,name,gender,locale,birthday,picture&access_token={model.AccessToken}");

            var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse);

            // 4. ready to create the local user account (if necessary) and jwt
            var user = await accountManager.UserManager.FindByEmailAsync(userInfo.Email);

            if (user == null)
            {
                var appUser = new ApplicationUser
                {
                    FirstName  = userInfo.FirstName,
                    LastName   = userInfo.LastName,
                    FacebookId = userInfo.Id,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    PictureUrl = userInfo.Picture.Data.Url
                };

                var result = await accountManager.UserManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8));

                if (!result.Succeeded)
                {
                    var sb = new StringBuilder();
                    foreach (var item in result.Errors)
                    {
                        sb.Append($"{item.Code}: {item.Description}.");
                    }

                    return(new BadRequestObjectResult(new { error = sb.ToString() }));
                }
            }

            // generate the jwt for the local user...
            var localUser = await accountManager.UserManager.FindByNameAsync(userInfo.Email);

            //var roles = await _userManager.GetRolesAsync(localUser);  ---- NOT WORKING ?!?!?
            IEnumerable <string> roles = accountManager.GetUserRoleNames(localUser);;

            if (localUser == null)
            {
                return(new BadRequestObjectResult(new { error = "Failed to create local user account." }));
            }

            var jwt = await Token.GenerateJwt(
                jwtFactory.GenerateClaimsIdentity(localUser.UserName, localUser.Id, roles),
                jwtFactory,
                localUser.UserName,
                jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });

            return(new OkObjectResult(jwt));
        }
        public async Task <IActionResult> Facebook([FromBody] FacebookAuthDto model)
        {
            // 1.generate an app access token
            var appAccessTokenResponse = await Client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={_fbAuthSettings.AppId}&client_secret={_fbAuthSettings.AppSecret}&grant_type=client_credentials");

            var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse);
            // 2. validate the user access token
            var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={model.AccessToken}&access_token={appAccessToken.AccessToken}");

            var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse);

            if (!userAccessTokenValidation.Data.IsValid)
            {
                return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid facebook token.", ModelState)));
            }

            // 3. we've got a valid token so we can request user data from fb
            var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v2.8/me?fields=id,email,first_name,last_name,name,gender,locale,birthday,picture&access_token={model.AccessToken}");

            var facebookUserInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse);

            // 4. ready to create the local user account (if necessary) and jwt
            var user = await _userManager.KullaniciyiGetirEpostayaGore(facebookUserInfo.Email);

            string mesaj = string.Empty;

            if (user == null)
            {
                user = new Kullanici()
                {
                    UserName        = facebookUserInfo.Email,
                    Email           = facebookUserInfo.Email,
                    EmailConfirmed  = false,
                    YaratilmaTarihi = DateTime.Now,
                    Pasif           = true,
                    Yonetici        = false,
                    FacebookId      = facebookUserInfo.Id,
                    //FaceBookPictureUrl = userInfo.Picture.Data.Url
                };
                user.Kisi = new KullaniciKisi
                {
                    Unvan      = "Doç.Dr.",
                    Ad         = facebookUserInfo.FirstName,
                    Soyad      = facebookUserInfo.LastName,
                    CinsiyetNo = 1,

                    DogumTarihi = new DateTime(1970, 11, 15)
                };
                KisiyeFacebookFotografiEkle(facebookUserInfo, user);
                var result = await _userManager.CreateAsync(user, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8));

                if (!result.Succeeded)
                {
                    return(Ok(Sonuc.Basarisiz(new Hata[] { new Hata {
                                                               Kod = "", Tanim = "Facebook bilgileriyle kullanıcı yaratılamadı!"
                                                           } })));
                }
                else
                {
                    mesaj = "Facebook kullanıcısı yaratıldı. Hesabınız onay sürecinde. Lütfen Eposta adresinizi kontrol ediniz.";
                }
            }
            else
            {
                bool kayitGerekli = false;
                if (user.FacebookId == null || user.FacebookId != facebookUserInfo.Id)
                {
                    //user.Pasif = true;
                    //user.EmailConfirmed = false;
                    if (facebookUserInfo.Gender == "male")
                    {
                        user.Kisi.CinsiyetNo = 1;
                    }
                    else if (facebookUserInfo.Gender == "female")
                    {
                        user.Kisi.CinsiyetNo = 2;
                    }

                    kayitGerekli = true;
                }

                var facebookFotograflari = user.Kisi.Fotograflari.Where(f => f.DisKaynakId == "facebook").ToList();
                var facebookFotografiYok = facebookFotograflari != null && !facebookFotograflari.Any(fb => fb.Url == facebookUserInfo.Picture.Data.Url);

                var suankiProfilFotografi = user.Kisi.Fotograflari.SingleOrDefault(f => f.ProfilFotografi);
                if (suankiProfilFotografi != null)
                {
                    suankiProfilFotografi.ProfilFotografi = false;
                    kayitGerekli = true;
                }

                if (facebookFotografiYok)
                {
                    KisiyeFacebookFotografiEkle(facebookUserInfo, user);
                    kayitGerekli = true;
                }


                if (kayitGerekli)
                {
                    var degistirmeSonuc = await _userManager.UpdateAsync(user);

                    if (!degistirmeSonuc.Succeeded)
                    {
                        return(Ok(Sonuc.Basarisiz(new Hata[] { new Hata {
                                                                   Kod = "", Tanim = "Facebook bilgileriyle kullanıcı kaydedilemedi!"
                                                               } })));
                    }
                    else
                    {
                        mesaj = "Facebook bilgileriyle kullanıcı var olan kullanıcı ilişkilendirildi. Hesabınızı onaylanması gerekli. Lütfen eposta adresinizi kontrol ediniz.";
                    }
                }
            }

            // generate the jwt for the local user...
            var localUser = await _userManager.KullaniciyiGetirEpostayaGore(facebookUserInfo.Email);



            if (localUser == null)
            {
                return(Ok(Sonuc.Basarisiz(new Hata[] { new Hata {
                                                           Kod = "Giris Başarısız", Tanim = "Facebook bilgileriyle lokal kullanıcı hesabı yaratılamadı!"
                                                       } })));
            }

            var girisYapabilirSonuc = await signInManager.CanSignInAsync(localUser);

            if (girisYapabilirSonuc)
            {
                if (!localUser.EmailConfirmed)
                {
                    //Eposta konfirme etme süreci başlasın
                }
            }
            if (!localUser.Pasif)
            {
                //Aktifleştirme süreci başlasın
            }

            var jwt = await Tokens.GenerateJwt(_jwtFactory.GenerateClaimsIdentity(localUser),
                                               _jwtFactory, localUser.UserName, _jwtOptions);

            var kullaniciDto = user.ToKullaniciBilgi();

            var sonuc = KayitSonuc <object> .IslemTamam(new { tokenString = jwt, kullanici = kullaniciDto });

            sonuc.Mesajlar[0] = $"Hoşgeldiniz {kullaniciDto.TamAdi}!";
            sonuc.Mesajlar.Add(mesaj);
            return(Ok(sonuc));
        }
        public async Task <IActionResult> Facebook([FromBody] FacebookAuthViewModel model)
        {
            // 1.generate an app access token
            var appAccessTokenResponse = await _httpClient.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={_fbAuthSettings.AppId}&client_secret={_fbAuthSettings.AppSecret}&grant_type=client_credentials");

            var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse);
            // 2. validate the user access token
            var userAccessTokenValidationResponse = await _httpClient.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={model.AccessToken}&access_token={appAccessToken.AccessToken}");

            var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse);

            if (!userAccessTokenValidation.Data.IsValid)
            {
                return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid facebook token.", ModelState)));
            }

            // 3. we've got a valid token so we can request user data from fb
            var userInfoResponse = await _httpClient.GetStringAsync($"https://graph.facebook.com/v2.8/me?fields=id,email,first_name,last_name,name,gender,locale,birthday,picture&access_token={model.AccessToken}");

            var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse);

            // 4. ready to create the local user account (if necessary) and jwt
            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user == null)
            {
                var appUser = new AppUser
                {
                    FirstName  = userInfo.FirstName,
                    LastName   = userInfo.LastName,
                    FacebookId = userInfo.Id,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    PictureUrl = userInfo.Picture.Data.Url
                };

                var result = await _userManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8));

                if (!result.Succeeded)
                {
                    return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState)));
                }

                await _appDbContext.Customers.AddAsync(new Customer { IdentityId = appUser.Id, Location = "", Locale = userInfo.Locale, Gender = userInfo.Gender });

                await _appDbContext.SaveChangesAsync();
            }

            // generate the jwt for the local user...
            var localUser = await _userManager.FindByNameAsync(userInfo.Email);

            if (localUser == null)
            {
                return(BadRequest(Errors.AddErrorToModelState("login_failure", "Failed to create local user account.", ModelState)));
            }

            var jwt = await Tokens.GenerateJwt(_jwtFactory.GenerateClaimsIdentity(localUser.UserName, localUser.Id),
                                               _jwtFactory, localUser.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });

            return(new OkObjectResult(jwt));
        }
Exemple #12
0
        public async Task <IActionResult> Login([FromBody] LoginRequest request)
        {
            Response <RegisteredUserResponse> response = new Response <RegisteredUserResponse>();

            try
            {
                if (!ModelState.IsValid)
                {
                    var requestResponse = ApiResponseFormatter.RequestResponse(ModelState);
                    return(BadRequest(requestResponse));
                }

                User     userCredentials;
                DateTime dateRegistered;
                using (var _context = new MiniSurveyContext())
                {
                    userCredentials = await _context.Users.Where(x => x.EmailAddress == request.Email.Trim())
                                      .FirstOrDefaultAsync();
                }

                if (userCredentials == null)
                {
                    response = new Response <RegisteredUserResponse>
                    {
                        ResponseBody = new SuccessResponse <RegisteredUserResponse>
                        {
                            Data            = null,
                            ResponseCode    = "E001",
                            ResponseMessage = "Your email and password combination was incorrect, kindly try again later."
                        }
                    };
                    return(Unauthorized(response.ResponseBody));
                }

                bool isPassword = userCredentials != null && _cryptographyService.ValidateHash(request.Password, userCredentials.PasswordSalt, userCredentials.PasswordHash);
                if (!isPassword)
                {
                    response = new Response <RegisteredUserResponse>
                    {
                        ResponseBody = new SuccessResponse <RegisteredUserResponse>
                        {
                            Data            = null,
                            ResponseCode    = "E001",
                            ResponseMessage = "Your email and password combination was incorrect, kindly try again later."
                        }
                    };
                    return(Unauthorized(response.ResponseBody));
                }

                var identity = _jwtFactory.GenerateClaimsIdentity(userCredentials.EmailAddress, userCredentials.Id.ToString());
                var jwtToken = await ValueGenerator.GenerateJwt(identity, _jwtFactory, userCredentials.EmailAddress, _jwtOptions.Value, new JsonSerializerSettings { Formatting = Formatting.None });

                // deserialize generated auth token to be passed to client application.
                var authToken = JsonConvert.DeserializeObject <Token>(jwtToken);

                response = new Response <RegisteredUserResponse>
                {
                    ResponseBody = new SuccessResponse <RegisteredUserResponse>
                    {
                        Data = new RegisteredUserResponse {
                            User = new Dto.UserResponse {
                                Email = userCredentials.EmailAddress, Name = userCredentials.Name, DateRegistered = userCredentials.DateRegistered
                            }, Role = new DefaultResponse {
                                Id = userCredentials.RoleId, Value = HelperFunctions.GetRole(userCredentials.RoleId)
                            }
                        },
                        ResponseCode    = "00",
                        ResponseMessage = "You have been successfully enrolled to participate in the survey."
                    }
                };


                return(Ok(response.ResponseBody));
            }
            catch (Exception)
            {
                response = new Response <RegisteredUserResponse>
                {
                    ResponseBody = new SuccessResponse <RegisteredUserResponse>
                    {
                        Data            = null,
                        ResponseCode    = "E001",
                        ResponseMessage = "Sorry, we are unable to process your request at the moment, kindly try again later."
                    }
                };
                return(StatusCode(500, response.ResponseBody));
            }
        }
        public async Task <IActionResult> GoogleLogin([FromBody] GoogleLoginViewModel vm)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var user = await _userManager.FindByEmailAsync(vm.email);

            string password = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8);

            if (user == null)
            {
                var u = new GXUser()
                {
                    Email      = vm.email,
                    UserName   = vm.email,
                    googleId   = vm.googleId,
                    photoUrl   = vm.photoUrl,
                    firstName  = vm.name,
                    gender     = "",
                    dateJoined = DateTime.Now
                };

                var result = await _userManager.CreateAsync(u, password);

                if (!result.Succeeded)
                {
                    return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState)));
                }

                user = await _userManager.FindByEmailAsync(vm.email);
            }
            else
            {
                user.googleId = vm.googleId;
                user.photoUrl = vm.photoUrl;
                _context.Users.Update(user);
                await _context.SaveChangesAsync();
            }

            var identity = await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(user.UserName, user.Id));

            var jwt = await Tokens.GenerateJwt(identity, _jwtFactory, user.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });


            return(Ok(new
            {
                Id = user.Id,
                userName = user.UserName,
                firstName = user.firstName,
                lastName = user.lastName,
                email = user.Email,
                facebookId = user.facebookId,
                gender = user.gender,
                twitterId = user.twitterId,
                googleId = user.googleId,
                birthDate = user.birthDate,
                photoUrl = !string.IsNullOrEmpty(user.photoUrl) ? user.photoUrl : "/assets/images/profile-pic.png",
                token = jwt
            }));
        }
Exemple #14
0
        public async Task <IActionResult> Facebook([FromBody] FacebookAuthViewModel model)
        {
            var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(
                await GetHttpResponse(_fbAuthSettings.GetAppAccessUrl())
                );
            var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(
                await GetHttpResponse(_fbAuthSettings.GetUserAccessUrl(model.AccessToken, appAccessToken.AccessToken))
                );
            var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(
                await GetHttpResponse(_fbAuthSettings.GetUserInfoUrl(model.AccessToken))
                );

            if (!userAccessTokenValidation.Data.IsValid)
            {
                return(BadRequest(
                           Errors.AddErrorToModelState("login_failure", "Invalid facebook token.", ModelState)
                           ));
            }

            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user == null)
            {
                var roleId  = _roleManager.FindByNameAsync("User").Id;
                var newUser = new User
                {
                    FirstName  = userInfo.FirstName,
                    LastName   = userInfo.LastName,
                    FacebookId = userInfo.Id,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    Photo      = userInfo.Picture.Data.Url,
                };

                var result = await _userManager.CreateAsync(newUser, "123qweR!");

                if (!result.Succeeded)
                {
                    return(BadRequest(
                               Errors.AddErrorsToModelState(result, ModelState)
                               ));
                }
            }

            var localUser = await _userManager.FindByNameAsync(userInfo.Email);

            if (localUser == null)
            {
                return(BadRequest(
                           Errors.AddErrorToModelState("login_failure", "Failed to create local user account.", ModelState)
                           ));
            }

            var jwt = await Tokens.GenerateJwt(
                _jwtFactory.GenerateClaimsIdentity(localUser.UserName, localUser.Id.ToString()),
                _jwtFactory,
                localUser.UserName,
                _jwtOptions,
                new JsonSerializerSettings { Formatting = Formatting.Indented }
                );

            return(Ok(jwt));
        }
        public async Task <JwtToken> Login([FromBody] Login credentials,
                                           [FromServices] SignInManager <User> signInManager,
                                           [FromServices] RoleManager <Role> roleManager,
                                           [FromServices] IJwtFactory jwtFactory,
                                           [FromServices] IOptions <JwtIssuerOptions> jwtOptions,
                                           [FromServices] IOptions <ServerOptions> serverOptions,
                                           [FromServices] IServiceProvider serviceProvider)
        {
            JwtToken ret = null;

            var result = await signInManager.PasswordSignInAsync(credentials.UserName, credentials.Password, false, lockoutOnFailure : true);

            if (result.Succeeded)
            {
                var user = (await signInManager.UserManager.FindByNameAsync(credentials.UserName));

                ClaimsIdentity identity = null;

                if (serverOptions.Value.UseMultiTenancy)
                {
                    using (var scope = serviceProvider.CreateScope())
                    {
                        var claimStore     = scope.ServiceProvider.GetRequiredService <IMultiTenantUserClaimStore <User, long> >();
                        var roleStore      = scope.ServiceProvider.GetRequiredService <IMultiTenantUserRoleStore <User, long> >();
                        var roleClaimStore = scope.ServiceProvider.GetRequiredService <IMultiTenantRoleClaimStore <Role, long> >();

                        var roles = await roleStore.GetRolesAsync(user, CancellationToken.None);

                        var roleClaims = new Dictionary <long, IList <Claim> >();

                        foreach (var rolePair in roles)
                        {
                            roleClaims.Add(rolePair.Key, new List <Claim>());
                            foreach (var role in rolePair.Value)
                            {
                                var _role = await roleManager.FindByNameAsync(role);

                                var claims = await roleClaimStore.GetClaimsAsync(_role, rolePair.Key, CancellationToken.None);

                                foreach (var claim in claims)
                                {
                                    roleClaims[rolePair.Key].Add(claim);
                                }
                            }
                        }

                        identity = jwtFactory.GenerateClaimsIdentity(user, roles, await claimStore.GetClaimsAsync(user, CancellationToken.None), roleClaims);
                    }
                }
                else
                {
                    var roles = await signInManager.UserManager.GetRolesAsync(user);

                    var roleClaims = new List <Claim>();

                    foreach (var role in roles)
                    {
                        var _role = await roleManager.FindByNameAsync(role);

                        roleClaims.AddRange(await roleManager.GetClaimsAsync(_role));
                    }

                    identity = jwtFactory.GenerateClaimsIdentity(user, roles, await signInManager.UserManager.GetClaimsAsync(user), roleClaims);
                }

                ret = await identity.GenerateJwt(jwtFactory, jwtOptions.Value, user.Id);
            }
            else
            {
                throw new Exception("Login failed");
            }

            return(ret);
        }
Exemple #16
0
        private async Task <ClaimsIdentity> GetClaimsIdentity(ApplicationUser applicationUser)
        {
            var roles = await _userManager.GetRolesAsync(applicationUser);

            return(await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(applicationUser.UserName, applicationUser.Id, new System.Collections.Generic.List <string>(roles))));
        }
Exemple #17
0
        public async Task <IActionResult> Google([FromBody] FacebookAuthViewModel model)
        {
            int    mark = 1;
            string d    = "info";

            try{
                mark++;
                var values = new Dictionary <string, string>();
                values.Add("code", model.AccessToken);
                values.Add("client_id", "313078532206-b01t045uahrop8264g97jrnt1j2dmbrt.apps.googleusercontent.com");
                values.Add("client_secret", "YZjprBnuzhD1K31y3F4reKXj");
                values.Add("redirect_uri", "http://localhost:5000/facebook-auth.html");
                values.Add("grant_type", "authorization_code");
                mark++;
                var appAccessTokenResponse = await Client.PostAsync("https://accounts.google.com/o/oauth2/token", new FormUrlEncodedContent(values));

                mark++;
                if (appAccessTokenResponse.StatusCode != HttpStatusCode.OK)
                {
                    return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid google token.", ModelState)));
                }
                mark++;
                d = "a1";
                var res = await appAccessTokenResponse.Content.ReadAsStringAsync();

                d = "a2";
                var appAccessToken = JsonConvert.DeserializeObject <TokenPreseneter>(res);
                d = "a3";

                var userInfoResp = await Client.GetStringAsync($"https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token={appAccessToken.AccessToken}");

                d = "a4";
                var userInfo = JsonConvert.DeserializeObject <GoogleUserInfo>(userInfoResp);
                d = "a5->" + userInfoResp;
                var user = await _userManager.FindByEmailAsync(userInfo.Email);

                d = "a6";
                mark++;
                if (user == null)
                {
                    var appUser = new AppUser
                    {
                        FirstName  = userInfo.GivenName,
                        LastName   = userInfo.FamilyName,
                        Email      = userInfo.Email,
                        UserName   = userInfo.Email,
                        PictureUrl = userInfo.Picture
                    };
                    mark++;
                    var result = await _userManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8));

                    if (!result.Succeeded)
                    {
                        return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState)));
                    }
                    _userManager.AddDefaultClaims(appUser);
                }
                mark++;
                // generate the jwt for the local user...
                var localUser = await _userManager.FindByNameAsync(userInfo.Email);

                if (localUser == null)
                {
                    return(BadRequest(Errors.AddErrorToModelState("login_failure", "Failed to create local user account.", ModelState)));
                }
                mark++;
                var claims = await _userManager.GetClaimsAsync(localUser);

                var identity = _jwtFactory.GenerateClaimsIdentity(localUser.UserName, claims.ToArray());
                var jwt      = await Tokens.GenerateJwt(identity, _jwtFactory, localUser.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });

                return(new OkObjectResult(jwt));
            }
            catch (Exception ex) {
                return(BadRequest(Errors.AddErrorToModelState($"unhandled error:{mark}{d}", ex.Message, ModelState)));
            }
        }
        private async Task <JwtRefreshTokenModel> _processUserDetails(FacebookUserData userInfo)
        {
            // 4. ready to create the local user account (if necessary) and jwt
            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user is null)
            {
                var appUser = new ApplicationUser {
                    FirstName  = userInfo.FirstName,
                    LastName   = userInfo.LastName,
                    FacebookId = userInfo.Id,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    PictureUrl = userInfo.Picture.Data.Url
                };
                var result = await _userManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8));

                if (!result.Succeeded)
                {
                    throw new InvalidOperationException(
                              ModelState.ToString()
                              );
                }
            }
            else
            {
                user.PictureUrl = userInfo.Picture.Data.Url;
                var result = await _userManager.UpdateAsync(user);

                if (!result.Succeeded)
                {
                    throw new InvalidOperationException(
                              ModelState.ToString()
                              );
                }
            }

            // generate the jwt for the local user...
            var localUser = await _userManager.FindByNameAsync(userInfo.Email);

            if (localUser is null)
            {
                throw new InvalidOperationException(
                          ModelState.ToString()
                          );
            }
            var roles = await _userManager.GetRolesAsync(localUser);

            var jwt = await TokenIssuer.GenerateJwt(
                _jwtFactory.GenerateClaimsIdentity(localUser.UserName, localUser.Id),
                _jwtFactory,
                localUser.UserName,
                roles.ToArray <string>(),
                _jwtOptions,
                new JsonSerializerSettings { Formatting = Formatting.Indented });

            var refresh = TokenIssuer.GenerateRefreshToken(128);

            user.AddRefreshToken(
                refresh,
                _contextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());

            await _unitOfWork.CompleteAsync();

            return(new JwtRefreshTokenModel(refresh, jwt));
        }
Exemple #19
0
        public async Task <string> GenerateJWT(string user, string id, int plantId, int sectorId, int jobId)
        {
            var identity = _jwtFactory.GenerateClaimsIdentity(user, id, plantId, sectorId, jobId);

            return(await Tokens.GenerateJwt(identity, _jwtFactory, user, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented }));
        }
 private ClaimsIdentity GetClaimsIdentity(AppUser user)
 {
     return(jwtFactory.GenerateClaimsIdentity(user.UserName, user.Id));
 }
Exemple #21
0
        private async Task GenerateToken(HttpContext context)
        {
            var username = context.Request.Form["Username"][0].Trim();
            var password = context.Request.Form["Password"][0].Trim();

            if (string.IsNullOrEmpty(password) && string.IsNullOrEmpty(username))
            {
                context.Response.ContentType = "application/json";
                context.Response.StatusCode  = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync(JsonConvert.SerializeObject(new { ErrorMessage = new List <string>()
                                                                                    {
                                                                                        ResponseMessageModel.AuthenticateUser.UserNameRequired, ResponseMessageModel.AuthenticateUser.PasswordRequired
                                                                                    } }, new JsonSerializerSettings {
                    Formatting = Formatting.Indented
                }));

                return;
            }
            else if (string.IsNullOrEmpty(username))
            {
                context.Response.ContentType = "application/json";
                context.Response.StatusCode  = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync(JsonConvert.SerializeObject(new { ErrorMessage = new List <string>()
                                                                                    {
                                                                                        ResponseMessageModel.AuthenticateUser.UserNameRequired
                                                                                    } }, new JsonSerializerSettings {
                    Formatting = Formatting.Indented
                }));

                return;
            }
            else if (string.IsNullOrEmpty(password))
            {
                context.Response.ContentType = "application/json";
                context.Response.StatusCode  = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync(JsonConvert.SerializeObject(new { ErrorMessage = new List <string>()
                                                                                    {
                                                                                        ResponseMessageModel.AuthenticateUser.PasswordRequired
                                                                                    } }, new JsonSerializerSettings {
                    Formatting = Formatting.Indented
                }));

                return;
            }

            using (var serviceScope = _serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                _userManager = serviceScope.ServiceProvider.GetService <UserManager <ApplicationUser> >();
                var result = await _userManager.FindByNameAsync(username);

                if (result == null)
                {
                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode  = (int)HttpStatusCode.BadRequest;
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(new { ErrorMessage = new List <string>()
                                                                                        {
                                                                                            ResponseMessageModel.AuthenticateUser.UserAuthFail
                                                                                        } }, new JsonSerializerSettings {
                        Formatting = Formatting.Indented
                    }));

                    return;
                }

                if (await _userManager.CheckPasswordAsync(result, password))
                {
                    _applicationDbContext = serviceScope.ServiceProvider.GetService <ApplicationDbContext>();
                    List <ProjectModel> listProject = _applicationDbContext.UserAndProjects.Where(x => x.UserId == result.Id)?.Select(y => new ProjectModel()
                    {
                        Id = y.ProjectId, Name = y.Project.Name
                    }).ToList();
                    string projectIds = listProject.Count > 0 ? string.Join(",", listProject.Select(x => x.Id)) : string.Empty;
                    var    role       = await _userManager.GetRolesAsync(result);

                    var claimIdentity = _jwtFactory.GenerateClaimsIdentity(username, result.Id, result.IsAdmin, projectIds, role.Count > 0 ? role[0].ToString() : "");
                    var jwt           = await Tokens.GenerateJwt(claimIdentity, _jwtFactory, username, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });


                    var response = new Response <dynamic>
                    {
                        Code    = HttpStatusCode.OK,
                        Message = string.Empty,
                        Data    = new
                        {
                            Access_Token = jwt,
                            User         = new
                            {
                                Username    = username,
                                ProjectList = listProject,
                                result.FirstName,
                                result.LastName,
                                ProfileImageUrl = (!string.IsNullOrWhiteSpace(result.ProfilePhoto))? $"{_appSettings.FolderPath.Path}/{result.ProfilePhoto}": $"{_appSettings.FolderPath.Path}/noimage.gif",
                                UserRole        = result.IsAdmin.HasValue ? "Admin" : "User",
                                UserId          = result.Id,
                                RedirectUrl     = result.IsAdmin.HasValue && string.IsNullOrEmpty(result.AccessToken) ? GenerateAuthorizeUrl() : string.Empty
                            }
                        }
                    };

                    // Serialize and return the response
                    context.Response.ContentType = "application/json";
                    if (result.IsAdmin.HasValue && string.IsNullOrEmpty(result.AccessToken))
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Redirect;
                    }
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                        Formatting = Formatting.Indented
                    }));
                }
                else
                {
                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode  = (int)HttpStatusCode.BadRequest;
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(new { ErrorMessage = new List <string>()
                                                                                        {
                                                                                            ResponseMessageModel.AuthenticateUser.UserAuthFail
                                                                                        } }, new JsonSerializerSettings {
                        Formatting = Formatting.Indented
                    }));

                    return;
                }
            }
        }
Exemple #22
0
        public async Task <IActionResult> Facebook([FromBody] FacebookModel model)
        {
            var userInfo = new FacebookUserData();

            try
            {
                var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v3.0/me?fields=id,email,first_name,last_name,gender,locale,birthday,picture&access_token={model.AccessToken}");

                userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse);
            }
            catch (Exception ex)
            {
                return(new BadRequestObjectResult(new List <ErrorViewModel>()
                {
                    new ErrorViewModel()
                    {
                        Code = "InvalidToken", Description = "Facebook token is not valid."
                    }
                }));
            }
            if (userInfo.Picture != null)
            {
                try
                {
                    var imageResponse = await Client.GetStringAsync($"https://graph.facebook.com/v3.0/{userInfo.Id}/picture?type=album&redirect=false");

                    var image = JsonConvert.DeserializeObject <FacebookPictureData>(imageResponse);
                    userInfo.Picture = image;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
            var existingUser = await _userManager.FindByEmailAsync(userInfo.Email);

            if (existingUser == null)
            {
                var user = new ApplicationUser
                {
                    FacebookId  = userInfo.Id,
                    Email       = userInfo.Email,
                    UserName    = userInfo.FirstName + userInfo.LastName,
                    PictureUrl  = userInfo.Picture?.Data?.Url,
                    Visibility  = true,
                    Nationality = "US"
                };

                if (userInfo.Gender != null)
                {
                    user.Gender = userInfo.Gender.Equals("male") ? Gender.Male : userInfo.Gender.Equals("female") ? Gender.Female : Gender.Other;
                }
                else
                {
                    user.Gender = Gender.None;
                }
                if (userInfo.Birthday != DateTime.MinValue)
                {
                    var dateOfBirth = new DateTime(day: userInfo.Birthday.Day, month: userInfo.Birthday.Month, year: DateTime.Now.Year);
                    if (DateTime.Now >= dateOfBirth)
                    {
                        user.Age = DateTime.Now.Year - userInfo.Birthday.Year;
                    }
                    else
                    {
                        user.Age = DateTime.Now.Year - userInfo.Birthday.Year - 1;
                    }
                }

                user.UserName = UserExtensions.RemoveDiacritics(user.UserName);
                var result = await _userManager.CreateAsync(user, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8));

                if (!result.Succeeded)
                {
                    return(new BadRequestObjectResult(result.Errors));
                }
                else
                {
                    existingUser = await _userManager.FindByNameAsync(user.UserName);
                }
            }

            var jwt = await Tokens.GenerateJwt(_jwtFactory.GenerateClaimsIdentity(existingUser.UserName, existingUser.Id),
                                               _jwtFactory, existingUser.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented }, existingUser.ProfileComplete);

            return(new OkObjectResult(jwt));
        }