Ejemplo n.º 1
0
        public async Task <IResultModel <UserLoginViewModel> > GetResult(UserToTokenViewModel model)
        {
            var result = new UserResponseViewModel {
                Error = null, Result = new UserLoginViewModel()
            };

            try
            {
                var token = await _ctx.Tokens.Include(u => u.User).FirstOrDefaultAsync(x => x.Value == model.Token);

                var user = token.User;

                if (user == null)
                {
                    throw new Exception("Пользователь не найден");
                }

                result.Result.Token = _ctx.Tokens.Include(u => u.User).FirstOrDefault(x => x.User.Id == user.Id)?.Value;
                result.Result.Name  = user.UserName;
            }
            catch (Exception e)
            {
                result.Error = e.Message;
            }

            return(result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates the user response and changes status RequestedItem in which this UserResponse be created.
        /// </summary>
        /// <param name="userResponseModel">The user response model.</param>
        /// <returns>Requested Detail View Model</returns>
        public UserResponseViewModel CreateUserResponse(UserResponseViewModel userResponseModel)
        {
            try
            {
                var userResponse = new UserResponse
                {
                    Description     = userResponseModel.Description,
                    RequestedItemId = userResponseModel.RequestedItemId,
                    StatusId        = this._unitOfWork.StatusRepository.GetStatusByName(StuffStatus.New).Id
                };

                if (userResponseModel.UserId != 0)
                {
                    userResponse.UserId = userResponseModel.UserId;
                }

                var addedUserResponse = this._unitOfWork.UserResponseRepository.Create(userResponse);

                this._unitOfWork.SaveChanges();

                var addedUserResponseModel = userResponseModel;
                addedUserResponseModel.Id = addedUserResponse.Id;
                return(addedUserResponseModel);
            }

            catch (Exception ex)
            {
                throw new BusinessLogicException(ex.Message);
            }
        }
Ejemplo n.º 3
0
        public async Task <IResultModel <UserLoginViewModel> > GetResult(LoginViewModel model)
        {
            var result = new UserResponseViewModel {
                Error = null, Result = new UserLoginViewModel()
            };

            try
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user == null)
                {
                    throw new Exception("Пользователь не найден");
                }

                var isPasswordOk = await _userManager.CheckPasswordAsync(user, model.Password);

                if (!isPasswordOk)
                {
                    throw new Exception("Пароль введен не верно");
                }
                result.Result.Token = _ctx.Tokens.Include(u => u.User).FirstOrDefault(x => x.User.Id == user.Id)?.Value;
                result.Result.Name  = user.UserName;
            }
            catch (Exception e)
            {
                result.Error = e.Message;
            }

            return(result);
        }
Ejemplo n.º 4
0
        public IActionResult Report(string id, int year, int cId = 0)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return(View(null));
            }

            var user = _context.Users.FirstOrDefault(u => u.Id == id);

            //hakee kaikki userit kannasta ottaa ekan idn perusteella
            // //Lisäksi kaikki vastaukset saadaan listalle
            //Otetaan kaikki

            var responses = _context.Responses.Where(r => r.UserId == id && r.AnswerDate > DateTime.Now.AddDays(-90))
                            .Include(r => r.Assessment)
                            .ThenInclude(a => a.Category)
                            .Include(r => r.Assessment)
                            .ThenInclude(a => a.ResponseOptions).ToList();

            //Otettaan kaikki kysymykset
            var assessments = responses.Select(r => r.Assessment);
            //Otetaan kaikki kysymys kategoriat kertaalleeen (distinct)
            var categories = assessments.Select(a => a.Category).Distinct().ToList();



            // Swap here listan ensimmäiseksi alkioksi listan eka
            if (cId != 0 && categories.Count() > 0)
            {
                var tmp = categories.FirstOrDefault(c => c.Id == cId);
                //tempin indexi laatikoiden sisälle
                categories[categories.IndexOf(tmp)] = categories[0];
                categories[0] = tmp;
            }

            var model = new UserResponseViewModel()
            {
                Year       = year,
                User       = user,
                Categories = categories
            };


            // var model = new UserResponseViewModel(){
            //     User= _context.Users.FirstOrDefault(u => u.Id==id),
            //     Responses=_context.Responses.Where(r => r.AssessmentId==responseid).ToList()
            //     //Group= _context.Groups.Include(g => g.CategoryGroups).ThenInclude(cg => cg.Category).ThenInclude(c => c.Assessments).FirstOrDefault(g => g.Id == id)
            // };
            // model.Assessments = _context.Responses.Include(r => r.Assessment).Select(r => r.Assessment).Distinct().ToList();

            //todo
            //model.GroupResponses = _context.Responses.Include(r => r.Assessment).ThenInclude(a => a.Category).ThenInclude(c => c.CategoryGroups.Where(cg => model.User.UserGroups.Select(u => u.GroupId).Contains(cg.GroupId))).ToList();
            return(View(model)); //model
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> CreateUserResponse([FromBody] UserResponseViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(ValidationProblem(ModelState));
            }

            AppUser user = await userManager.FindByNameAsync(viewModel.UserName);

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

            var currentUserId  = 123;
            var createDateTime = DateTime.Now;

            IList <UserResponseQuestionAndAnswer> questionAnswerList = new List <UserResponseQuestionAndAnswer>();

            foreach (var questionAnswer in viewModel.UserResponseQuestionAndAnswerViewModels)
            {
                UserResponseQuestionAndAnswer userResponseQuestionAndAnswer = new UserResponseQuestionAndAnswer
                {
                    UserCreateId = currentUserId,
                    CreateDate   = createDateTime,
                    QuestionText = questionAnswer.QuestionText,
                    AnswerText   = questionAnswer.AnswerText,
                    QuestionNo   = questionAnswer.QuestionNo
                };
                questionAnswerList.Add(userResponseQuestionAndAnswer);
            }

            UserResponse userResponse = new UserResponse
            {
                UserCreateId = currentUserId,
                CreateDate   = createDateTime,
                UserId       = currentUserId,
                SurveyName   = viewModel.SurveyName,
                User         = user,
                UserResponseQuestionsAndAnswers = questionAnswerList
            };

            try
            {
                context.UserResponses.Add(userResponse);
                await context.SaveChangesAsync();

                return(Created("/Survey/UserResponse", viewModel));
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> GetUserResponseList(string surveyName, string userName)
        {
            if (string.IsNullOrEmpty(surveyName) && string.IsNullOrEmpty(userName))
            {
                return(ValidationProblem(MessageInfo.UserResponse_WrongData));
            }

            AppUser user = await userManager.FindByNameAsync(userName);

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

            IQueryable <UserResponse> userResponses = context.UserResponses
                                                      .Include(a => a.UserResponseQuestionsAndAnswers)
                                                      .Where(s => s.SurveyName == surveyName && s.UserId == user.Id)
                                                      .OrderByDescending(o => o.CreateDate)
                                                      .Take(3);

            if (!userResponses.Any())
            {
                return(NotFound());
            }

            IList <UserResponseViewModel> userResponsesList = new List <UserResponseViewModel>();

            foreach (var userResponse in userResponses)
            {
                IList <UserResponseQuestionAndAnswerViewModel> questionsAnswersList =
                    new List <UserResponseQuestionAndAnswerViewModel>();
                foreach (var questionAnswer in userResponse.UserResponseQuestionsAndAnswers)
                {
                    UserResponseQuestionAndAnswerViewModel qa = new UserResponseQuestionAndAnswerViewModel
                    {
                        QuestionText = questionAnswer.QuestionText,
                        AnswerText   = questionAnswer.AnswerText,
                        QuestionNo   = questionAnswer.QuestionNo
                    };
                    questionsAnswersList.Add(qa);
                }
                UserResponseViewModel viewModel = new UserResponseViewModel
                {
                    SurveyName     = userResponse.SurveyName,
                    UserName       = userResponse.User.UserName,
                    DateCompleting = userResponse.CreateDate,
                    UserResponseQuestionAndAnswerViewModels = questionsAnswersList
                };
                userResponsesList.Add(viewModel);
            }
            return(Ok(userResponsesList));
        }
Ejemplo n.º 7
0
        public async Task <ActionResult> Login(UserRequestViewModel user)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            try
            {
                UserResponseViewModel loggedInUser = await _userService.GetUserForLogin(user);

                if (loggedInUser != null)
                {
                    var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                    identity.AddClaim(new Claim(ClaimTypes.Name, loggedInUser.FirstName + " " + loggedInUser.LastName));
                    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, loggedInUser.CNP));
                    identity.AddClaim(new Claim(ClaimTypes.PrimarySid, loggedInUser.Id));
                    identity.AddClaim(new Claim(ClaimTypes.Role, "User"));

                    if (loggedInUser.IsAdmin)
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
                    }

                    identity.AddClaim(new Claim("UserId", loggedInUser.Id));

                    var authProperties = new AuthenticationProperties
                    {
                        AllowRefresh = true,
                        ExpiresUtc   = DateTimeOffset.Now.AddDays(1),
                        IsPersistent = true,
                    };

                    var claimsPrincipal = new ClaimsPrincipal(identity);

                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, authProperties);

                    return(RedirectToAction("Index", "Home"));
                }
            }
            catch (UserNotFoundException)
            {
                ModelState.Clear();
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View("Login", user));
            }

            return(null);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> GetUserResponse(string surveyName, string userName)
        {
            if (string.IsNullOrWhiteSpace(surveyName) && string.IsNullOrWhiteSpace(userName))
            {
                return(ValidationProblem(MessageInfo.UserResponse_WrongData));
            }

            AppUser user = await userManager.FindByNameAsync(userName);

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

            var userResponse = await context.UserResponses
                               .Include(a => a.UserResponseQuestionsAndAnswers)
                               .OrderBy(o => o.CreateDate)
                               .LastOrDefaultAsync(s => s.SurveyName == surveyName && s.UserId == user.Id);

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

            IList <UserResponseQuestionAndAnswerViewModel> questionsAnswersList =
                new List <UserResponseQuestionAndAnswerViewModel>();

            foreach (var questionAnswer in userResponse.UserResponseQuestionsAndAnswers)
            {
                UserResponseQuestionAndAnswerViewModel qa = new UserResponseQuestionAndAnswerViewModel
                {
                    QuestionText = questionAnswer.QuestionText,
                    AnswerText   = questionAnswer.AnswerText,
                    QuestionNo   = questionAnswer.QuestionNo
                };
                questionsAnswersList.Add(qa);
            }
            UserResponseViewModel viewModel = new UserResponseViewModel
            {
                SurveyName     = userResponse.SurveyName,
                UserName       = userResponse.User.UserName,
                DateCompleting = userResponse.CreateDate,
                UserResponseQuestionAndAnswerViewModels = questionsAnswersList
            };

            return(Ok(viewModel));
        }
Ejemplo n.º 9
0
        public IActionResult UserLogin([FromBody] LoginViewModel logindetails)
        {
            User user = new User();
            UserResponseViewModel userResponseViewModel = new UserResponseViewModel();

            List <User> users = new List <User>();

            users = _dBContext.User.ToList();

            user = users.Where(x => x.Email == logindetails.email.ToLower()).FirstOrDefault();

            if (user == null)
            {
                user             = new User();
                user.Name        = logindetails.name;
                user.Email       = logindetails.email;
                user.Password    = string.Empty;
                user.PhotoUrl    = logindetails.platformdetail.platformImage;
                user.Github      = logindetails.platformdetail.platform == "github" ? logindetails.platformdetail.platformid : string.Empty;
                user.Google      = logindetails.platformdetail.platform == "google" ? logindetails.platformdetail.platformid : string.Empty;
                user.Facebook    = logindetails.platformdetail.platform == "facebook" ? logindetails.platformdetail.platformid : string.Empty;
                user.CreatedTime = DateTime.UtcNow;
                user.Status      = 1;
                user.UserGuid    = Guid.NewGuid().ToString();

                _dBContext.User.Add(user);
                int result = _dBContext.SaveChanges();
            }

            if (user.Status == 0)
            {
                return(BadRequest(Messages.Inactiveusererror));
            }

            if (logindetails.platformdetail.platform.ToLower() == "google" && string.IsNullOrEmpty(user.Google))
            {
                user.Google = logindetails.platformdetail.platformid;
                _dBContext.User.Update(user);
                _dBContext.SaveChanges();
            }
            if (logindetails.platformdetail.platform.ToLower() == "facebook" && string.IsNullOrEmpty(user.Facebook))
            {
                user.Facebook = logindetails.platformdetail.platformid;
                _dBContext.User.Update(user);
                _dBContext.SaveChanges();
            }
            if (logindetails.platformdetail.platform.ToLower() == "github" && string.IsNullOrEmpty(user.Github))
            {
                user.Github = logindetails.platformdetail.platformid;
                _dBContext.User.Update(user);
                _dBContext.SaveChanges();
            }

            if (logindetails.platformdetail.platform.ToLower() == "google" && user.Google == logindetails.platformdetail.platformid ||
                logindetails.platformdetail.platform.ToLower() == "github" && user.Github == logindetails.platformdetail.platformid ||
                logindetails.platformdetail.platform.ToLower() == "facebook" && user.Facebook == logindetails.platformdetail.platformid)
            {
                userResponseViewModel.profileUrl = user.PhotoUrl;
                userResponseViewModel.userName   = user.Name;
                userResponseViewModel.userEmail  = user.Email;
                string encryptedString = Security.Encrypt(user.UserGuid);
                userResponseViewModel.UserGuid = encryptedString;

                _memoryCache.Set(encryptedString, user);
            }
            else
            {
                return(BadRequest(Messages.Inactiveusererror));
            }
            return(Ok(userResponseViewModel));
        }
Ejemplo n.º 10
0
 public UserResponseViewModel SetUserResponse([FromBody] UserResponseViewModel userResponse)
 {
     return(this._requestedItemService.CreateUserResponse(userResponse));
 }
Ejemplo n.º 11
0
        public async Task <IHttpActionResult> Get(string userName)
        {
            UserResponseViewModel user = await _userRepo.GetUser(userName);

            return(Ok(user));
        }
        public async Task <IActionResult> PostDeliveryBoyVerification([FromForm] LoginRequestViewModel value)
        {
            int    userId    = 0;
            string userIdStr = User.FindFirstValue(ClaimTypes.Name);

            if (!string.IsNullOrWhiteSpace(userIdStr))
            {
                userId = Convert.ToInt32(userIdStr);
            }

            var dd = User.Identity.Name;

            var model    = new UserResponseViewModel();
            var response = new SingleResponse <UserResponseViewModel>();

            if (ModelState.IsValid)
            {
                if (!(await _unit.IUser.Exists(u => u.PhoneNumber == value.MobileNo)).UserObject)
                {
                    ModelState.AddModelError("PEmail", "Phone No. Not register");
                    response.Message = "Phone no. does not register";
                    response.Status  = true;
                }
                else
                {
                    var Id         = (await _unit.IUser.GetSelectedAsync(t => t.PhoneNumber.Equals(value.MobileNo) && t.UserType == 2, m => m.Id)).UserObject;
                    var resultdata = await _userManager.FindByIdAsync(Convert.ToString(Id));

                    string strPhone = ("91" + value.MobileNo);
                    resultdata.FCMToken     = value.FcmToken;
                    resultdata.DeviceId     = value.DeviceId;
                    resultdata.DeviceType   = value.DeviceType;
                    resultdata.ModifiedDate = DateTime.Now;

                    response.Message = "user registered.";
                    response.Status  = true;
                    var otpresposedata = await _smsHandler.VerifyOtpAsync(mobile : strPhone, OTP : value.OTP);

                    if (otpresposedata.type == "success")
                    {
                        try
                        {
                            await _userManager.UpdateAsync(resultdata);

                            model.Name     = resultdata.FullName;
                            model.EmailId  = resultdata.Email;
                            model.MobileNo = resultdata.PhoneNumber;
                            if (!string.IsNullOrEmpty(resultdata.CustomerImage))
                            {
                                model.userImageProfileImage = resultdata.CustomerImage;
                            }
                            if (resultdata != null)
                            {
                                JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
                                byte[] key = Encoding.ASCII.GetBytes(_appSettings.Secret);
                                SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
                                {
                                    Subject = new ClaimsIdentity(new Claim[]
                                    {
                                        new Claim(ClaimTypes.Name, Id.ToString()),
                                        new Claim(ClaimTypes.MobilePhone, resultdata.PhoneNumber.ToString())
                                    }),
                                    Expires            = DateTime.UtcNow.AddDays(180),
                                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                                                SecurityAlgorithms.HmacSha256Signature)
                                };
                                SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
                                model.Token = tokenHandler.WriteToken(token);
                                // remove password before returning
                                value.OTP        = null;
                                response.Data    = model;
                                response.Message = "OTP verifed successfully";
                                response.Status  = true;
                                return(response.ToHttpResponse());
                            }
                            else
                            {
                                response.Message       = "Worng OTP";
                                response.Status        = false;
                                response.ErrorTypeCode = (int)ErrorMessage.WorngOTP;
                                return(response.ToHttpResponse());
                            }
                        }
                        catch (Exception ex)
                        {
                            response.Status  = false;
                            response.Message = "There was an internal error, please contact to technical support.";
                            ErrorTrace.Logger(LogArea.ApplicationTier, ex);
                            return(response.ToHttpResponse());
                        }
                    }
                }
            }
            return(response.ToHttpResponse());
        }