Example #1
0
        public async Task <ActionResult <UserResponseModel> > logIn(LogInRequestModel user)
        {
            Users checkUser = await userGymMovesRepository.getUser(user.username.Trim());

            /* If null, no user with that username exists.*/
            if (checkUser == null)
            {
                return(NotFound("Nobody with that username exists."));
            }

            /* Verify correct password has been entered.*/
            if (verifyHash(SHA256.Create(), user.password + checkUser.Salt, checkUser.Password))
            {
                UserResponseModel response = new UserResponseModel();
                response.userType    = checkUser.UserType;
                response.name        = checkUser.Name;
                response.gymMemberID = checkUser.MembershipId;
                response.gymID       = checkUser.GymIdForeignKey;

                return(Ok(response));
            }
            else
            {
                return(Unauthorized("Password is incorrect."));
            }
        }
Example #2
0
        public HttpResponseMessage RegisterUser(RegisterUserModel model)
        {
            return(this.ExecuteOperationAndHandleExceptions(() =>
            {
                var context = new GameContext();
                var dbUser = UserPersister.GetUserByUsernameAndDisplayName(model.Username, model.Nickname, context);
                if (dbUser != null)
                {
                    throw new InvalidOperationException("This user already exists in the database");
                }

                dbUser = new User()
                {
                    Username = model.Username.ToLower(),
                    Nickname = model.Nickname,
                    AuthCode = model.AuthCode,
                    Role = context.Roles.Where(r => r.Name == "user").FirstOrDefault()
                };
                context.Users.Add(dbUser);
                dbUser.SessionKey = UserPersister.GenerateSessionKey(dbUser.Id);

                context.SaveChanges();

                var responseModel = new UserResponseModel()
                {
                    Nickname = dbUser.Nickname,
                    SesionKey = dbUser.SessionKey
                };

                var response = this.Request.CreateResponse(HttpStatusCode.Created, responseModel);
                return response;
            }));
        }
        public IHttpActionResult Get(string id)
        {
            if (id == null)
            {
                return this.BadRequest("Provided username cannot be null!");
            }

            var ratings =  this.data.Ratings.All()
                .Where(r => r.User.UserName == id)
                .ToList();

            var sumOfAllRatings = 0;
            foreach (var rating in ratings)
            {
                sumOfAllRatings += rating.Value;
            }

            string userId = this.data.Users.All().FirstOrDefault(u => u.UserName == id).Id;
            int ratingsCount = ratings.Count();
            double averageRating = sumOfAllRatings * 1.0 / ratingsCount;

            var userToReturn = new UserResponseModel()
            {
                UserName = id,
                Rating = ratingsCount == 0 ? 0 : averageRating,
                Comments = this.data.Comments.All().Where(c => c.UserId == userId).ToList().Count,
                RealEstates = this.data.RealEstates.All().Where(re => re.UserId == userId).ToList().Count(),
            };

            return this.Ok(userToReturn);
        }
        public IActionResult Login(LoginModel model)
        {
            IEnumerable <User> userlist = _userRepository.FindByCondition(x => x.Email == model.Email);

            User user = new User();

            if (userlist.Count() > 0)
            {
                user = userlist.Single(x => x.Email == model.Email);
            }


            if (user == null)
            {
                return(BadRequest("Incorrect Information"));
            }
            else
            {
                if (user.Password == model.Password)
                {
                    UserResponseModel response = ViewModelConverter.UserDTOTOUserResponseModel(user);
                    return(Ok(response));
                }
                else
                {
                    return(BadRequest("Incorrect information"));
                }
            }
        }
Example #5
0
        public async Task <IActionResult> GetUsers(int id)
        {
            Users _user = await _userRepository.GetUser(id);

            if (_user == null)
            {
                List <ValidationMessageModel> _validationMessages = new List <ValidationMessageModel>();
                _validationMessages.Add(new ValidationMessageModel
                {
                    Code    = "Id",
                    Key     = "Id",
                    Message = "Id Not Found"
                });
                ProblemReporter.ReportResourseNotfound(JsonConvert.SerializeObject(_validationMessages));
            }

            UserResponseModel _result = new UserResponseModel
            {
                CreatedDate = _user.CreatedDate,
                Email       = _user.Email,
                FirstName   = _user.FirstName,
                Id          = _user.Id,
                LastName    = _user.LastName,
                Phone       = _user.Phone,
                Role        = _user.Role.Role
            };

            return(Ok(_result));
        }
Example #6
0
        public async Task <IActionResult> PostUsers([FromBody] UserPostModel model)
        {
            Roles _role = await _roleRepository.getRole(model.RoleId);

            if (_role == null)
            {
                List <ValidationMessageModel> _validationMessages = new List <ValidationMessageModel>();
                _validationMessages.Add(new ValidationMessageModel
                {
                    Code    = "RoleId",
                    Key     = "RoleId",
                    Message = "RoleId Is Invalid"
                });
                ProblemReporter.ReportBadRequest(JsonConvert.SerializeObject(_validationMessages));
            }

            Users _user = await _userRepository.InsertUser(model);

            UserResponseModel _result = new UserResponseModel
            {
                Id          = _user.Id,
                CreatedDate = _user.CreatedDate,
                Email       = _user.Email,
                FirstName   = _user.FirstName,
                LastName    = _user.LastName,
                Phone       = _user.Phone,
                Role        = _user.Role.Role
            };

            return(Ok(_result));
        }
        public async Task <ActionResult <long> > SignUp(UserDto userDto)
        {
            SignUpResponseModel signUpResponseModel = new SignUpResponseModel();


            if (userDto != null)
            {
                //User Already Exists
                UserResponseModel userResponseModel = _userRepository.GetUserByUserEmail(userDto.Email);
                if (userResponseModel != null && userResponseModel.Data != null && userResponseModel.Data.Count > 0)
                {
                    signUpResponseModel.StatusCode = 409;
                    signUpResponseModel.Message    = "User Already Exists!";
                    signUpResponseModel.UserID     = 0;
                    signUpResponseModel.ClassCode  = "0";
                }
                else
                {
                    DataTable userDataTable           = TranslateUserDtoToDataTable(userDto);
                    DataTable userEducationDataTable  = TranslateUserEducationDtoToDataTable(userDto.userEducation);
                    DataTable userExperienceDataTable = TranslateUserExperienceDtoToDataTable(userDto.userExperience);
                    DataTable userGuardianDataTable   = TranslateUserGuardianDtoToDataTable(userDto.userGuardian);
                    signUpResponseModel = _userRepository.SignUp(userDataTable, userEducationDataTable, userExperienceDataTable, userGuardianDataTable);
                }
            }
            signUpResponseModel.ClassCode = "0";
            return(Ok(signUpResponseModel));
        }
Example #8
0
        public async Task <UserResponseModel> AddUser(UserRequestModel requestModel)
        {
            var dbUser = await _userRepository.GetUserByName(requestModel.FullName);

            if (dbUser != null)
            {
                throw new Exception("User already existed");
            }

            var user = new Users
            {
                Email    = requestModel.Email,
                Password = requestModel.Password,
                FullName = requestModel.FullName
            };

            var createdUser = await _userRepository.AddAsync(user);

            var response = new UserResponseModel
            {
                Id       = createdUser.Id,
                Email    = createdUser.Email,
                FullName = createdUser.FullName
            };

            return(response);
        }
        public static List <UserResponseModel> ToUsers(DbDataReader dataReader)
        {
            List <UserResponseModel> users = new List <UserResponseModel>();

            while (dataReader.Read())
            {
                var userResponseModel = new UserResponseModel()
                {
                    UserId             = int.Parse(dataReader["id"].ToString()),
                    FirstName          = dataReader["firstName"].ToString(),
                    LastName           = dataReader["lastName"].ToString(),
                    Email              = dataReader["email"].ToString(),
                    ContactNumber      = dataReader["contactNumber"].ToString(),
                    Gender             = dataReader["gender"].ToString(),
                    IsAdmin            = bool.Parse(dataReader["isAdmin"].ToString()),
                    RoleId             = int.Parse(dataReader["roleId"].ToString()),
                    RoleName           = dataReader["role_name"].ToString(),
                    DepartmentId       = int.Parse(dataReader["departmentId"].ToString()),
                    DepartmentName     = dataReader["department_name"].ToString(),
                    ReportingManagerId = int.Parse(dataReader["reportingManagerId"].ToString()),
                    ReportingManager   = dataReader["manager"].ToString()
                };

                users.Add(userResponseModel);
            }
            ;

            users = users.OrderBy(x => x.FirstName).ToList();
            return(users);
        }
        public static UserResponseModel ToUser(DbDataReader dataReader)
        {
            UserResponseModel userResponseModel = null;

            if (dataReader.Read())
            {
                userResponseModel = new UserResponseModel()
                {
                    UserId             = int.Parse(dataReader["id"].ToString()),
                    FirstName          = dataReader["firstName"].ToString(),
                    LastName           = dataReader["lastName"].ToString(),
                    Email              = dataReader["email"].ToString(),
                    ContactNumber      = dataReader["contactNumber"].ToString(),
                    Gender             = dataReader["gender"].ToString(),
                    IsAdmin            = bool.Parse(dataReader["isAdmin"].ToString()),
                    RoleId             = int.Parse(dataReader["roleId"].ToString()),
                    RoleName           = dataReader["role_name"].ToString(),
                    DepartmentId       = int.Parse(dataReader["departmentId"].ToString()),
                    DepartmentName     = dataReader["department_name"].ToString(),
                    ReportingManagerId = int.Parse(dataReader["reportingManagerId"].ToString()),
                    ReportingManager   = dataReader["manager"].ToString()
                };
            }
            ;

            return(userResponseModel);
        }
        public IHttpActionResult Create(RegisterBindingModel registerUserModel)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState));
            }

            User userCreateModel = new User()
            {
                Email     = registerUserModel.Email,
                FirstName = registerUserModel.FirstName,
                LastName  = registerUserModel.LastName,
                UserName  = registerUserModel.UserName,
            };

            UserManager <User> userManager = this.GetUserManager();
            IdentityResult     result      = userManager.Create(userCreateModel, registerUserModel.Password);

            if (!result.Succeeded)
            {
                return(this.BadRequest(string.Join(" ", result.Errors)));
            }

            UserResponseModel responseModel = this.context.Users.Find(userCreateModel.Id).MapUserToViewModel();

            return(this.Created("/", responseModel));
        }
        /// <summary>
        /// Declare get specific UserData all detailes method
        /// </summary>
        /// <param name="EmailId">Passing email id string</param>
        /// <returns>return user model object</returns>
        public UserResponseModel GetSpecificEmployeeAllDetailes(string EmailId)
        {
            try
            {
                UserResponseModel UserData = new UserResponseModel();

                SqlCommand sqlCommand = new SqlCommand("spGetAllUserData", this.sqlConnectionVariable);
                sqlCommand.CommandType = CommandType.StoredProcedure;
                this.sqlConnectionVariable.Open();
                SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

                while (sqlDataReader.Read())
                {
                    UserData.EmailId = sqlDataReader["EmailId"].ToString();
                    if (EmailId == UserData.EmailId)
                    {
                        UserData.Firstname      = sqlDataReader["FirstName"].ToString();
                        UserData.Lastname       = sqlDataReader["LastName"].ToString();
                        UserData.EmpId          = Convert.ToInt32(sqlDataReader["EmpId"]);
                        UserData.CurrentAddress = sqlDataReader["LocalAddress"].ToString();
                        UserData.MobileNumber   = sqlDataReader["MobileAddress"].ToString();
                        UserData.Gender         = sqlDataReader["Gender"].ToString();
                        UserData.DayAndTime     = sqlDataReader["DayAndTime"].ToString();
                        break;
                    }
                }
                this.sqlConnectionVariable.Close();
                return(UserData);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Example #13
0
        public UserResponseModel GetUserById(int id)
        {
            try
            {
                UserModel userModel = UserRepository.GetUserById(id);

                if (userModel != null)
                {
                    UserResponseModel userResponseModel = new UserResponseModel()
                    {
                        UserId   = userModel.UserId,
                        RoleId   = userModel.RoleId,
                        Username = userModel.Username,
                        Password = userModel.Password
                    };

                    return(userResponseModel);
                }
            }
            catch (Exception ex)
            {
                Logger.LogFile($"Error getting a User by id = {id}: {ex.Message}");
            }

            return(null);
        }
        public void PutTest()
        {
            User user = GetUser();
            UpdateUserRequestModel    userRequest        = GetUpdateUserRequestModel();
            UserResponseModel         userResponse       = GetUserResponseModel();
            ValidationResponse <User> validationResponse = GetOkValidationResponse();

            _mockMapper
            .Setup(mapper => mapper.Map <UpdateUserRequestModel, User>(userRequest))
            .Returns(user);

            _mockService
            .Setup(serv => serv.Update(user))
            .Returns(validationResponse);

            _mockMapper
            .Setup(mapper => mapper.Map <User, UserResponseModel>(validationResponse.ResponseData))
            .Returns(userResponse);

            IActionResult actionResult = _controller.Put(_userId, userRequest);

            OkObjectResult actual     = (OkObjectResult)actionResult;
            string         actualName = ((UserResponseModel)actual.Value).FullName;

            Assert.Equal(user.FullName, actualName);
            Assert.Equal(StatusCodes.Status200OK, actual.StatusCode);
        }
Example #15
0
        public static UserResponseModel ToModel(this User user, IMediaService mediaService, MediaSettings mediaSettings)
        {
            var model = new UserResponseModel()
            {
                Id               = user.Id,
                FirstName        = user.FirstName,
                LastName         = user.LastName,
                Name             = user.Name,
                DateCreatedUtc   = user.DateCreated,
                DateCreatedLocal = DateTimeHelper.GetDateInUserTimeZone(user.DateCreated, DateTimeKind.Utc, user),
                UserName         = user.UserName,
                CoverImageUrl    = mediaService.GetPictureUrl(user.GetPropertyValueAs <int>(PropertyNames.DefaultCoverId), PictureSizeNames.MediumCover),
                ProfileImageUrl  = mediaService.GetPictureUrl(user.GetPropertyValueAs <int>(PropertyNames.DefaultPictureId), PictureSizeNames.MediumProfileImage),
                Active           = user.Active
            };

            if (!string.IsNullOrEmpty(model.CoverImageUrl) && !string.IsNullOrEmpty(model.ProfileImageUrl))
            {
                return(model);
            }

            if (string.IsNullOrEmpty(model.CoverImageUrl))
            {
                model.CoverImageUrl = mediaSettings.DefaultUserProfileCoverUrl;
            }
            if (string.IsNullOrEmpty(model.ProfileImageUrl))
            {
                model.ProfileImageUrl = mediaSettings.DefaultUserProfileImageUrl;
            }

            return(model);
        }
Example #16
0
        /// <summary>
        ///  Get User By Email/UserName
        /// </summary>
        /// <param name="email"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public UserResponseModel GetUserByRole(LoginViewModel loginVM)
        {
            var userData    = new UserResponseModel();
            var getUserData = (from user in _unitOfwork.UserRepository.GetAll()
                               join roleRelation in _unitOfwork.UserRoleRelationRepository.GetAll() on user.UserID equals roleRelation.Fk_UserId
                               join role in _unitOfwork.UserRoleRepository.GetAll() on roleRelation.Fk_RoleId equals role.RoleId
                               where user.Email == loginVM.UserName
                               select new { UserResponseModel = user, RoleResponseModel = role }).ToList();

            if (getUserData.Count > 0)
            {
                AutoMapper.Mapper.CreateMap <User, UserResponseModel>();
                userData = AutoMapper.Mapper.Map <User, UserResponseModel>(getUserData.FirstOrDefault().UserResponseModel);
                userData.RoleResponseModel = new List <RoleResponseModel>();
                foreach (var itemData in getUserData)
                {
                    AutoMapper.Mapper.CreateMap <UserRole, RoleResponseModel>();
                    var roleData = AutoMapper.Mapper.Map <UserRole, RoleResponseModel>(itemData.RoleResponseModel);
                    userData.RoleResponseModel.Add(roleData);
                }
                userData.HasError     = false;
                userData.ErrorMessage = string.Empty;
                return(userData);
            }
            userData.HasError     = true;
            userData.ErrorMessage = "User not found";
            return(userData);
        }
        public IHttpActionResult getblog([FromUri] string userName)
        {
            var _oRet = new UserResponseModel();

            try
            {
                var uu = UserData.GetUser(userName);

                if (uu != null)
                {
                    _oRet.IsSuccess   = true;
                    _oRet.UserName    = userName;
                    _oRet.Message     = "Autenticación de cuenta de usuario realizada satisfactoriamente.";
                    _oRet.StatusCode  = (int)HttpStatusCode.OK;
                    _oRet.AccessToken = TokenGenerator.GenerateTokenJwt(userName);
                    _oRet.ExpiresIn   = DateTime.Now.AddMinutes(Utilerias.JWT_Expire_Minutes()).ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss");
                }
                else
                {
                    _oRet.IsSuccess  = false;
                    _oRet.Message    = "La cuenta de usuario " + userName + " no existe.";
                    _oRet.StatusCode = (int)HttpStatusCode.BadRequest;
                }
            }
            catch (Exception oEx)
            {
                _oRet.IsSuccess  = false;
                _oRet.Message    = "Error interno del servidor. Lamentamos las molestias ocasionadas. Favor de reportarlo al Administrador del Sistema. Detalle del error: " + oEx.Message.Trim();
                _oRet.StatusCode = (int)HttpStatusCode.InternalServerError;
            }

            // Finalmente retornamos el resultado.
            return(Ok(_oRet));
        }
Example #18
0
        public UserResponseModel GetUserByUsername(string username)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                return(null);
            }

            try
            {
                UserModel userModel = UserRepository.GetUserByUsername(username);

                if (userModel != null)
                {
                    UserResponseModel userResponseModel = new UserResponseModel()
                    {
                        UserId   = userModel.UserId,
                        RoleId   = userModel.RoleId,
                        Username = userModel.Username,
                        Password = userModel.Password
                    };

                    return(userResponseModel);
                }
            }
            catch (Exception ex)
            {
                Logger.LogFile($"Error getting a User by username = {username}: {ex.Message}");
            }

            return(null);
        }
        public string CreateToken(UserResponseModel model)
        {
            var claims = new List <Claim>()
            {
                new Claim("id", model.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.Email, model.Email),
                new Claim("fullname", model.Fullname),
                new Claim("mobileno", model.Mobileno)
            };
            //create identity object to store claims
            var identityClaims = new ClaimsIdentity();

            identityClaims.AddClaims(claims);

            //pick an hashing algorithm
            var creds   = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);
            var expires = DateTime.UtcNow.AddDays(_config.GetValue <int>("TokenSetting:Expiration"));

            //Token object: SecurityTokenDescriptor
            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject            = identityClaims,
                Expires            = expires,
                SigningCredentials = creds,
                Issuer             = _config["TokenSetting:Issuer"],
                Audience           = _config["TokenSetting:Audience"]
            };

            //Handler: JwtSecurityTokenHandler
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
        /// <summary>
        /// It Check whether the login data send by the user is correct or not.
        /// </summary>
        /// <param name="login">login parameter like email-id or password</param>
        /// <returns>It return the Response Model to be Send as Response</returns>
        public UserResponseModel Login(LoginRequest login)
        {
            try
            {
                login.Password = EncodeDecode.EncodePasswordToBase64(login.Password);
                var data = context.UserDetails.FirstOrDefault(user => (user.EmailId == login.EmailId) &&
                                                              (user.Password == login.Password) && user.UserRole == _user);

                if (data != null)
                {
                    var userData = new UserResponseModel()
                    {
                        UserId     = data.UserId,
                        FirstName  = data.FirstName,
                        LastName   = data.LastName,
                        EmailId    = data.EmailId,
                        ProfilePic = data.ProfilePic,
                        Type       = data.Type,
                        IsActive   = data.IsActive,
                        UserRole   = data.UserRole,
                        CreatedAt  = data.CreatedAt,
                        ModifiedAt = data.ModifiedAt
                    };
                    return(userData);
                }
                return(null);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
        public IEnumerable<UserResponseModel> GetUsers()
        {
            var users = this.data.Users.All().ToList();
            var listOfUsers = new List<UserResponseModel>();

            foreach (var user in users)
            {
                string userName = user.UserName;

                var ratings = this.data.Ratings.All()
                .Where(r => r.User.UserName == userName)
                .ToList();

                var sumOfAllRatings = 0;
                foreach (var rating in ratings)
                {
                    sumOfAllRatings += rating.Value;
                }

                int ratingsCount = ratings.Count();
                double averageRating = sumOfAllRatings * 1.0 / ratingsCount;

                var newResponseUser = new UserResponseModel()
                {
                    UserName = userName,
                    Rating = ratingsCount == 0 ? 0 : averageRating
                };
                listOfUsers.Add(newResponseUser);
            }

            return listOfUsers;
        }
        public void PostTest()
        {
            User user = GetUser();
            ValidationResponse <User> validationResponse = GetOkValidationResponse();
            AddUserRequestModel       userRequest        = GetAddUserRequestModel();
            UserResponseModel         userResponse       = GetUserResponseModel();

            _mockMapper
            .Setup(mapper => mapper.Map <AddUserRequestModel, User>(userRequest))
            .Returns(user);

            _mockService
            .Setup(serv => serv.Add(user))
            .Returns(validationResponse);

            _mockMapper
            .Setup(mapper => mapper.Map <User, UserResponseModel>(validationResponse.ResponseData))
            .Returns(userResponse);

            IActionResult actionResult = _controller.Post(userRequest);

            CreatedAtActionResult actual = (CreatedAtActionResult)actionResult;
            string actualName            = ((UserResponseModel)actual.Value).FullName;

            Assert.Equal(user.FullName, actualName);
            Assert.Equal(StatusCodes.Status201Created, actual.StatusCode);
        }
Example #23
0
        public async Task <IActionResult> Register(UserRegisterModel user)
        {
            if (ModelState.IsValid)
            {
                if (user == null)
                {
                    return(BadRequest($"{nameof(user)} cannot be null"));
                }

                ApplicationUser appUser = new ApplicationUser();
                appUser.UserName       = user.userName;
                appUser.Email          = user.email;
                appUser.EmailConfirmed = true;
                appUser.IsEnabled      = true;
                appUser.FullName       = user.fullName;

                var result = await _accountManager.CreateUserAsync(appUser, user.Roles, user.password);

                UserResponseModel resp = new UserResponseModel();
                resp.result = result.Item1;

                return(Ok(resp));
            }

            return(BadRequest(ModelState));
        }
Example #24
0
        public async Task <IActionResult> PutUser([FromRoute] string userId, [FromBody] UserRequestModel userModel)
        {
            var user = UserRequestModel.MapToUser(userModel, userId);
            await _userStore.SaveUserAsync(user);

            return(Ok(UserResponseModel.MapFrom(user, Url)));
        }
Example #25
0
        /// <summary>
        /// It Generate the token.
        /// </summary>
        /// <param name="userToken">Response Model</param>
        /// <param name="type">Token Type</param>
        /// <returns>it return Token</returns>
        private string GenerateToken(UserResponseModel userToken, string type)
        {
            try
            {
                var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
                var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

                var claims = new[]
                {
                    new Claim("UserId", userToken.UserId.ToString()),
                    new Claim("EmailId", userToken.EmailId.ToString()),
                    new Claim("TokenType", type),
                    new Claim("UserType", userToken.UserRole.ToString())
                };

                var token = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Issuer"],
                                                 claims, expires: DateTime.Now.AddDays(1), signingCredentials: credentials);

                return(new JwtSecurityTokenHandler().WriteToken(token));
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Example #26
0
        private UserResponseModel GenerateJwtToken
            (string email, IdentityUser user, IList <string> roles)
        {
            var dbUser   = _userRepository.GetUserByEmail(email, "app", _applicationSetting.CreateConnectionString());
            var authUser = _userRepository.GetAuthUserIdByEmail(email, _applicationSetting.AuthConnectionString());

            if (string.IsNullOrEmpty(authUser))
            {
                throw new Exception("The user does not exist.");
            }
            var instanceId = $"A_{authUser}".Replace("-", "_");
            //if (dbUser != null) instanceId = dbUser.InstanceId;
            var name    = dbUser == null ? email : dbUser.FullName;
            var picture = (dbUser == null ? "default" : dbUser.ProfilePicture) ?? "default";

            var claims = _minutzClaimManager.CreateClaims(email, picture, name, roles, instanceId, user.Id);

            var tokenStringResult = _minutzJwtSecurityTokenManager.JwtSecurityToken
                                        (_applicationSetting.ClientSecret, _applicationSetting.AuthorityDomain, claims);

            var userModel = new UserResponseModel
            {
                access_token = tokenStringResult.token,
                expires_in   = tokenStringResult.expires.ToString(CultureInfo.CurrentCulture),
                id_token     = tokenStringResult.token,
                scope        = string.Join(",", roles),
                token_type   = "aspnet"
            };

            return(userModel);
        }
Example #27
0
        public IActionResult Login([FromBody] LoginRequest login)
        {
            try
            {
                if (!ValidateLoginRequest(login))
                {
                    return(BadRequest(new { Message = "Enter Proper Input Value." }));
                }

                UserResponseModel data = _userBusiness.Login(login);
                bool   status          = false;
                string message;
                string token;
                if (data == null)
                {
                    message = "No User Present with this Email-Id and Password";
                    return(Ok(new { status, message }));
                }
                else
                {
                    status  = true;
                    message = "User Successfully Logged In";
                    token   = GenerateToken(data, _login);
                    return(Ok(new { status, message, data, token }));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(new { e.Message }));
            }
        }
Example #28
0
        public IActionResult ForgetPassword([FromBody] ForgetPasswordRequest forgetPassword)
        {
            try
            {
                if (!ValidateForgetPasswordRequest(forgetPassword))
                {
                    return(BadRequest(new { Message = "Please input the Data Properly." }));
                }

                UserResponseModel data = _userBusiness.ForgetPassword(forgetPassword);
                bool   status          = false;
                string message;
                string token;
                if (data == null)
                {
                    message = "No User Found with this Email-Id: " + forgetPassword.EmailId;
                    return(Ok(new { status, message }));
                }
                else
                {
                    token = GenerateToken(data, _forgetPassword);
                    MsmqSender.SendToMsmq(forgetPassword.EmailId, token);
                    status  = true;
                    message = "An Password Reset Link has been Send to the above Email";
                    return(Ok(new { status, message, token }));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(new { e.Message }));
            }
        }
Example #29
0
        public async Task <IActionResult> Registration([FromBody] RegisterRequest userDetails)
        {
            try
            {
                if (!ValidateRegisterRequest(userDetails))
                {
                    return(BadRequest(new { Message = "Enter Proper Data" }));
                }

                UserResponseModel data = await _userBusiness.Registration(userDetails);

                bool   status = false;
                string message;
                string token;
                if (data == null)
                {
                    message = "No Data Provided";
                    return(Ok(new { status, message }));
                }
                else
                {
                    status  = true;
                    message = "User Account Created Successfully";
                    token   = GenerateToken(data, "Registration");
                    return(Ok(new { status, message, data, token }));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(new { e.Message }));
            }
        }
        /// <summary>
        /// It will check whether the Provided Email id is present in the database or not.
        /// </summary>
        /// <param name="forgetPassword">Email-Id</param>
        /// <returns>It return the Response Model to be Send as Response</returns>
        public UserResponseModel ForgetPassword(ForgetPasswordRequest forgetPassword)
        {
            try
            {
                var data = context.UserDetails.FirstOrDefault(user => user.EmailId == forgetPassword.EmailId);

                if (data != null)
                {
                    var userData = new UserResponseModel()
                    {
                        UserId     = data.UserId,
                        FirstName  = data.FirstName,
                        LastName   = data.LastName,
                        EmailId    = data.EmailId,
                        ProfilePic = data.ProfilePic,
                        Type       = data.Type,
                        IsActive   = data.IsActive,
                        UserRole   = data.UserRole,
                        CreatedAt  = data.CreatedAt,
                        ModifiedAt = data.ModifiedAt
                    };
                    return(userData);
                }
                return(null);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Example #31
0
        public async Task <UserResponseModel> GetUserAsync(string email)
        {
            var user = await _userRepository.Query()
                       .Include(u => u.UserRoles)
                       .ThenInclude(ur => ur.Role)
                       .SingleOrDefaultAsync(u => u.Email == email);

            if (user == null)
            {
                throw new NotFoundException("User not found!");
            }

            var result = new UserResponseModel
            {
                Status  = true,
                Message = "Successful",
                Data    = new UserDto
                {
                    Email = user.Email,
                    Id    = user.Id,
                    Roles = user.UserRoles.Select(r => new RoleDto
                    {
                        Id          = r.RoleId,
                        Description = r.Role.Description,
                        Name        = r.Role.Name
                    })
                }
            };

            return(result);
        }
Example #32
0
        public async Task <UserGetResponseModel> Get(string id)
        {
            var result = await _mediator.Send(new UserGetCommand(id));

            var user = new UserResponseModel(result.User);

            return(new UserGetResponseModel(user));
        }
Example #33
0
        public ActionResult LogOn(UserResponseModel userResponseModel)
        {
            if (userResponseModel.Status != "ok")
                return RedirectToAction("Index");

            var account = Query.For<Account>()
                .With(new AccountPlayerIdCriterion(userResponseModel.Account_Id));

            if (account == null)
            {
                account = userResponseModel.MapTo(new Account(userResponseModel.Access_Token));
                AccountRepository.Add(account);
                TaskCreator.CreateTaskForAccount(account);
            }
            else
            {
                account.SetToken(userResponseModel.Access_Token);
            }

            AuthenticationService.LogIn(account);

            return RedirectToAction("Index", "Home");
        }
        public IHttpActionResult Put(UserResponseModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            var result = this.users.Update(
              model.UserName,
              model.AboutMe,
              model.Gender,
              model.IsWorking,
              model.DateOfBirth);

            return this.Ok(result);
        }