Esempio n. 1
0
        public async Task <ActionResult <UserDto> > Login(UserLoginDto userLoginDto)
        {
            try
            {
                //get user by email
                var user = await _userRepository.GetUserByEmail(userLoginDto.Email);

                if (user == null)
                {
                    return(Unauthorized(new RestError(HttpStatusCode.Unauthorized, new { Unauthorized = "Invalid email or password" })));
                }

                //confirm password
                var passwordConfirmed = await _userRepository.ConfirmPassword(user, userLoginDto.Password);

                //Return a token if password confirmed
                if (passwordConfirmed)
                {
                    var userDto = new UserDto
                    {
                        DisplayName = user.DisplayName,
                        Token       = _jwtGenerator.CreateToken(user),
                        Username    = user.UserName,
                        Manager     = user.Manager,
                        Admin       = user.Admin
                    };

                    //get last timestamp for LastJobsiteVisited
                    var lastJobsiteVisited = await _timestampRepository.GetUsersLastTimestamp(user);

                    if (lastJobsiteVisited != null)
                    {
                        userDto.LastJobsiteVisited = _mapper.Map <TimestampWithBasicJobsiteInfoDto>(lastJobsiteVisited);
                    }

                    //check to see if currently clocked in at a jobsite
                    var currentlyClockedin = await _timestampRepository.GetClockedInTimestamp(user);

                    if (currentlyClockedin != null)
                    {
                        userDto.CurrentlyClockedIn = true;
                        userDto.ClockedInTimestamp = _mapper.Map <TimestampClockedInBasicDto>(currentlyClockedin);
                    }

                    return(userDto);
                }
            }
            catch (Exception)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Server Error: Failed to communicate with database."));
            }
            //else
            return(Unauthorized(new RestError(HttpStatusCode.Unauthorized, new { Unauthorized = "Invalid email or password" })));
        }