Ejemplo n.º 1
0
        public async Task <IActionResult> Login(CustomerLoginDTO customerLoginDTO)
        {
            //  throw new Exception ("Say Hi NOO!");
            var customerFromRepo = await _repo.CustomerLogin(customerLoginDTO.Email.ToLower(), customerLoginDTO.Password);;

            if (customerFromRepo == null)
            {
                return(Unauthorized());
            }
            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, customerFromRepo.CustomerId.ToString()),
                new Claim(ClaimTypes.Email, customerFromRepo.Email)
            };
            var key  = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));
            var card = new SigningCredentials(key, SecurityAlgorithms.HmacSha512);
            var tokenDescriptions = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddHours(24),
                SigningCredentials = card
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptions);

            //var user = _mapper.Map<UserForListDto>(userFromRepo);
            return(Ok(new
            {
                token = tokenHandler.WriteToken(token),
                //user
            }));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> LogIn(CustomerLoginDTO model)
        {
            var returnUrl = model.returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                var result = await signInManager.PasswordSignInAsync(model.UserName,
                                                                     model.Password, model.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    return(LocalRedirect(returnUrl));
                }
                if (result.IsLockedOut)
                {
                    return(LocalRedirect("~/Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "کلمه کاربری یا رمز عبور اشتباست");
                    return(View(model));
                }
            }
            return(View(model));
        }
Ejemplo n.º 3
0
        public async Task <Dictionary <string, object> > Login(CustomerLoginDTO customerDTO)
        {
            Dictionary <string, object> res = new Dictionary <string, object>();

            if (string.IsNullOrEmpty(customerDTO.Username) || string.IsNullOrEmpty(customerDTO.Password))
            {
                res["status"]  = "failed";
                res["message"] = "用户名或密码不能为空!";
            }
            else
            {
                Customer customer = await Service.Login(customerDTO.Username, customerDTO.Password);

                if (customer == null)
                {
                    res["status"]  = "failed";
                    res["message"] = "用户名或密码错误!";
                }
                else
                {
                    res["status"] = "success";
                    res["token"]  = JWTTools.Encode(customer.Username, DateTime.Now.AddDays(1));
                }
            }
            return(res);
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> LoginAndRegisterCustomerV2([FromForm] CustomerLoginDTO model)
        {
            var userLogined = new UserLogined();

            if (ModelState.IsValid)
            {
                userLogined = await _authRepository.SignInAndSignUpCustomerAsync(model);
            }
            return(Ok(userLogined));
        }
        public ActionResult <Customer> LogIn(CustomerLoginDTO cred)
        {
            var cust = _repo.LogIn(cred);

            if (cust == null)
            {
                return(NotFound());
            }

            return(Ok(cust));
        }
        public IActionResult LoginControl([FromBody] CustomerLoginDTO customerLogin)
        {
            //return
            var customer = _customerService.GetCustomer(new Customer()
            {
                guid     = new Guid().ToString(), id = 0,
                Name     = customerLogin.Name,
                password = customerLogin.password,
                Surname  = customerLogin.Surname
            });

            return(Ok(customer));
        }
Ejemplo n.º 7
0
        public CustomerBasicDetail Login(CustomerLoginDTO customerRegDto)
        {
            CustomerBasicDetail detail = new CustomerBasicDetail();

            // ReSharper disable once ReplaceWithSingleCallToFirst
            Models.Customer _customer = db.Customers
                                        .Where(customer => customer.password == customerRegDto.password)
                                        .Where(customer => customer.email == customerRegDto.email)
                                        .First();
            detail.email      = _customer.email;
            detail.name       = _customer.name;
            detail.customerId = _customer.customerId;
            return(detail);
        }
Ejemplo n.º 8
0
 public bool RemoveCustomerLogin(CustomerLoginDTO removeEntity)
 {
     try
     {
         bool success = UOW.UserRepo.RemoveCustomerLogin(removeEntity);
         UOW.SaveChanges();
         return(success);
     }
     catch (Exception ex)
     {
         UOW.RollbackChanges();
         throw ex;
     }
 }
        public async Task <ApiResponse <CustomerInfoDTO> > Login(CustomerLoginDTO loginRequest)
        {
            ApiResponse <CustomerInfoDTO> result = new ApiResponse <CustomerInfoDTO>();

            try
            {
                Customer customer = await unitOfWork.CustomersManager.GetCustomerByPhoneNumber(loginRequest.MobileNumber);

                if (customer != null)
                {
                    if (customer.TotalNumberOfVisits == null)
                    {
                        customer.TotalNumberOfVisits = 1;
                        customer.LastVisitDate       = DateTime.Now;
                    }
                    else
                    {
                        customer.TotalNumberOfVisits++;
                        customer.LastVisitDate = DateTime.Now;
                    }


                    await unitOfWork.SaveChangesAsync();

                    CustomerInfoDTO customerInfo = new CustomerInfoDTO();
                    customerInfo.Id                  = customer.Id;
                    customerInfo.Name                = customer.Name;
                    customerInfo.LastBarberId        = customer.LastBarberId;
                    customerInfo.LastVisitDate       = customer.LastVisitDate;
                    customerInfo.TotalNumberOfVisits = customer.TotalNumberOfVisits;
                    customerInfo.PhoneNumber         = customer.PhoneNumber;

                    result.Data      = customerInfo;
                    result.Succeeded = true;
                    return(result);
                }
                result.Succeeded = false;
                result.Errors.Add("Phone number not registered , Kindly create a new account !");
                result.ErrorType = ErrorType.LogicalError;
                return(result);
            }
            catch (Exception ex)
            {
                result.Succeeded = false;
                result.Errors.Add(ex.Message);
                return(result);
            }
        }
Ejemplo n.º 10
0
        // GET api/<controller>/
        public IHttpActionResult Login(CustomerLoginDTO customerLogin)
        {
            var query = customerService.Login(customerLogin);

            if (query == null)
            {
                return(NotFound());
            }

            if (query.VerifyCode != 0)
            {
                return(BadRequest($"尚未通過驗證,{query.C_Id}"));
            }

            return(Ok(query));
        }
Ejemplo n.º 11
0
        public CustomerRegisterDTO Login(CustomerLoginDTO loginDTO)
        {
            var query = db.Customers.Where(a => a.C_Account == loginDTO.C_Account).SingleOrDefault();

            if (query != null)
            {
                if (PasswordCheck(query, loginDTO.C_Password))
                {
                    return(Mapper.Map <Customer, CustomerRegisterDTO>(query));
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 12
0
        public bool RemoveCustomerLogin(CustomerLoginDTO removeEntity)
        {
            try
            {
                string query = @"
                DELETE FROM CustomerLogins
                WHERE UserID = @UserID AND CustomerID = @CustomerID";

                var queryParameters = new DynamicParameters();
                queryParameters.Add("@UserID", removeEntity.UserID);
                queryParameters.Add("@CustomerID", removeEntity.CustomerID);

                int rowsDeleted = Connection.Execute(query, queryParameters, CurrentTrans);
                return((rowsDeleted > 0) ? true : false);
            }
            catch (Exception ex)
            {
                throw SqlExceptionHandler.HandleSqlException(ex) ?? ex;
            }
        }
Ejemplo n.º 13
0
        public async Task <ActionResult> Login(CustomerLoginDTO customerLoginDTO)
        {
            // https://code-maze.com/using-refresh-tokens-in-asp-net-core-authentication/
            if (customerLoginDTO == null)
            {
                return(BadRequest());
            }

            var customer = await _context.Customer.FirstOrDefaultAsync(c => (
                                                                           c.Username == customerLoginDTO.Username) &&
                                                                       (c.Password == customerLoginDTO.Password)
                                                                       );

            if (customer == null)
            {
                return(Unauthorized());
            }

            return(BuildToken(customerLoginDTO));
        }
Ejemplo n.º 14
0
        public IActionResult Login(CustomerLoginDTO customer)
        {
            //checking if the user is logged in
            var customerRepository = _customerRepository.Login(customer.username.ToLower(), customer.password);

            if (customerRepository == null)
            {
                return(Unauthorized());
            }

            //create claims that will be passed to a token

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, customerRepository.CustomerId.ToString()),
                new Claim(ClaimTypes.Name, customerRepository.Username)
            };

            //create a key to sign the token
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1), //Token expires in a day
                SigningCredentials = credentials
            };

            var TokenHandler = new JwtSecurityTokenHandler();

            var Token = TokenHandler.CreateToken(tokenDescriptor);

            //return the jwt token to the client
            return(Ok(new
            {
                token = TokenHandler.WriteToken(Token)
            }));
        }
Ejemplo n.º 15
0
        public bool AddCustomerLogin(CustomerLoginDTO createEntity)
        {
            try
            {
                string query = @"
                INSERT INTO CustomerLogins(UserID, CustomerID)
                VALUES (@UserID, @CustomerID)
                
                SELECT SCOPE_IDENTITY()";

                var queryParameters = new DynamicParameters();
                queryParameters.Add("@UserID", createEntity.UserID);
                queryParameters.Add("@CustomerID", createEntity.CustomerID);

                var returnID = Connection.QueryFirst <int>(query, queryParameters, CurrentTrans);
                return(returnID > 0);
            }
            catch (Exception ex)
            {
                throw SqlExceptionHandler.HandleSqlException(ex) ?? ex;
            }
        }
Ejemplo n.º 16
0
        private ActionResult BuildToken(CustomerLoginDTO customerLoginDTO)
        {
            // Get the secret key from appsettings
            var secretKey = _configuration.GetValue <string>("SecretKey");
            var key       = Encoding.UTF8.GetBytes(secretKey);
            var creds     = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256);

            var claims = new List <Claim> {
                new Claim(JwtRegisteredClaimNames.Sub, customerLoginDTO.Username),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var expiration = DateTime.UtcNow.AddHours(1);

            var token = new JwtSecurityToken(
                claims: claims,
                expires: expiration,
                signingCredentials: creds
                );

            return(Ok(new {
                token = new JwtSecurityTokenHandler().WriteToken(token)
            }));
        }
Ejemplo n.º 17
0
 public async Task <IActionResult> Login(CustomerLoginDTO loginRequest)
 {
     return(await AddItemResponseHandler(async() => await service.Login(loginRequest)));
 }
Ejemplo n.º 18
0
 public CustomerBasicDetail Login(CustomerLoginDTO customerRegDto)
 {
     return(_customerService.Login(customerRegDto));
 }
Ejemplo n.º 19
0
        public IActionResult LogIn()
        {
            var model = new CustomerLoginDTO();

            return(View(model));
        }
Ejemplo n.º 20
0
        public Customer LogIn(CustomerLoginDTO creditentials)
        {
            Customer cust = _context.Customer.FirstOrDefault(x => x.Username == creditentials.Login && x.Password == creditentials.Password);

            return(cust);
        }
Ejemplo n.º 21
0
        public async Task <UserLogined> SignInAndSignUpCustomerAsync(CustomerLoginDTO model)
        {
            // GET roleCustomerUser
            var roleCustomerUser = await _context.Roles.FirstOrDefaultAsync(role => role.RoleName.Equals(RoleTypeHelper.RoleCustomerUser));

            User userCreate = new User();

            // CheckUserExist
            var userExist = await _context.Users
                            .Include(u => u.UserToRoles)
                            .ThenInclude(x => x.Role)
                            .Where(u => u.UserToRoles.Any(x => x.RoleId == roleCustomerUser.Id))
                            .FirstOrDefaultAsync(u => u.Email.ToLower().Equals(model.Email.ToLower()) &&
                                                 u.UseExternalSignIns.Count > 0 && u.UserDevices.Count > 0);

            // case login lần sau:
            if (userExist != null)
            {
                // if exist then update user
                // update To UserDevices
                // update To UserExternalSignIns
                userCreate = userExist;
                _context.Entry(userCreate).State = EntityState.Modified;
                userCreate.LastLogin             = DateTime.UtcNow;
                // check appId & currentUserId Exist
                if (!_context.UserDevices.Any(uc => uc.CurrentUserId == userCreate.Id && uc.CodeDevice == model.AppId))
                {
                    // Add to UserDevices
                    var userDevice = new UserDevice
                    {
                        Id            = Guid.NewGuid().ToString(),
                        IsVerified    = (int)TypeVerified.Verified,
                        VerifiedCode  = (int)(DateTime.Now.Ticks >> 23),
                        CodeDevice    = model.AppId,
                        CurrentUserId = userCreate.Id,
                        LastLogin     = DateTime.UtcNow,
                        TimeCode      = 20
                    };
                    userCreate.UserDevices.Add(userDevice);
                }
                else
                {
                    // Update to UserDevices
                    var userDevice = _context.UserDevices.FirstOrDefault(uc => uc.CurrentUserId == userExist.Id && uc.CodeDevice == model.AppId);
                    if (userDevice != null)
                    {
                        _context.Entry(userDevice).State = EntityState.Modified;
                        userDevice.LastLogin             = DateTime.UtcNow;
                        // save tp db
                        await _context.SaveChangesAsync();
                    }
                }
                // check exist UseExternalSignIns
                if (!_context.ExternalSignIns.Any(ue => ue.UserId == userCreate.Id && ue.TypeLogin == model.TypeLogin))
                {
                    var newUSERExternalSignIn = new ExternalSignIn
                    {
                        Id            = Guid.NewGuid().ToString(),
                        IsVerified    = (int)TypeVerified.Verified,
                        LastLogin     = DateTime.UtcNow,
                        TimeLifeToken = 3600,
                        TokenLogin    = model.TokenLogin,
                        TypeLogin     = model.TypeLogin,
                        UserId        = userExist.Id
                    };
                    userCreate.UseExternalSignIns.Add(newUSERExternalSignIn);
                }
                else
                {
                    // update To UserExternalSignIns
                    var userExternalSignIn = _context.ExternalSignIns.FirstOrDefault(ue => ue.UserId == userExist.Id && ue.TypeLogin == model.TypeLogin);
                    if (userExternalSignIn != null)
                    {
                        _context.Entry(userExternalSignIn).State = EntityState.Modified;
                        userExternalSignIn.LastLogin             = DateTime.UtcNow;
                        // save tp db
                        await _context.SaveChangesAsync();
                    }
                }

                // save to db
                await _context.SaveChangesAsync();
            }
            else
            {
                // if not exist then create user
                userCreate.Id          = Guid.NewGuid().ToString();
                userCreate.FirstName   = model.FirstName;
                userCreate.LastLogin   = DateTime.UtcNow;
                userCreate.LastName    = model.LastName;
                userCreate.Email       = model.Email;
                userCreate.UserName    = model.Email;
                userCreate.PhoneNumber = model.PhoneNumber;

                var userDevice = new UserDevice
                {
                    Id            = Guid.NewGuid().ToString(),
                    CodeDevice    = model.AppId,
                    CurrentUserId = userCreate.Id,
                    IsVerified    = (int)TypeVerified.Verified,
                    LastLogin     = DateTime.UtcNow,
                    TimeCode      = 20,
                    VerifiedCode  = (int)(DateTime.Now.Ticks >> 23)
                };
                // Save to UserDevices
                userCreate.UserDevices.Add(userDevice);

                var externalSign = new ExternalSignIn
                {
                    Id            = Guid.NewGuid().ToString(),
                    IsVerified    = (int)TypeVerified.Verified,
                    LastLogin     = DateTime.UtcNow,
                    TimeLifeToken = 3600,
                    TokenLogin    = model.TokenLogin,
                    TypeLogin     = model.TypeLogin,
                    UserId        = userCreate.Id
                };
                // Save to ExternalSignIns
                userCreate.UseExternalSignIns.Add(externalSign);

                // Save to UserToRole
                var userToRole = new UserToRole();
                userToRole.Role = roleCustomerUser;
                userToRole.User = userCreate;
                roleCustomerUser.UserToRoles.Add(userToRole);
                _context.Users.Add(userCreate);

                // Save All To Database
                await _context.SaveChangesAsync();
            }
            // create token
            string currentUserId = Guid.NewGuid().ToString();
            var    userLogined   = CreateToken(userCreate, currentUserId);

            // save to login
            await SaveToUserLoginAsync(userCreate, userLogined, currentUserId);

            // save to login
            // return
            return(userLogined);
        }