예제 #1
0
        //Login function
        public async Task <LoginRespond> LoginServiceAsync(StudentLoginModel model)
        {
            //validation functions
            var context = new ValidationContext(model, serviceProvider: null, items: null);
            var results = new List <ValidationResult>();

            if (Validator.TryValidateObject(model, context, results, true))
            {
                string passwordEncoded = Encoder(model.Password);     //encode password

                return(await CheckInfoAsync(model, passwordEncoded)); //check whether user exists
            }
            else
            {
                //If validation failed
                LoginRespond loginRespond = new LoginRespond
                {
                    Pass      = false,
                    Email     = model.Email,
                    Token     = "Failed to login due to the incorrect email or password",
                    LoginTime = DateTime.Now
                };

                return(loginRespond);
            }
        }
예제 #2
0
        public async Task <object> StudentLogin([FromBody] StudentLoginModel model)
        {
            if (ModelState.IsValid)
            {
                var user = _dbContext.Users.Include(x => x.UserClass).SingleOrDefault(x => x.Email == model.Email);

                if (user != null)
                {
                    var result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password, false, false);

                    if (result.Succeeded)
                    {
                        var token = _dbContext.Token.Include(x => x.ClassRoom).SingleOrDefault(x => x.TokenValue == model.Token);
                        if (token == null)
                        {
                            return(Json(new JsonResponse(false, "No token with that value!")));
                        }

                        if (user.UserClass.Any(x => x.ClassRoomId == token.ClassId))
                        {
                            DateTime timeNow      = DateTime.Now;
                            DateTime durationTime = token.CreatedDateTime.AddMinutes(30);

                            double distFromKEA = Distance(latitudeKEA, longtitudeKEA, model.Latitude, model.Longtitude);

                            if (distFromKEA <= 3)
                            {
                                if ((timeNow <= durationTime))
                                {
                                    UserToken userToken = new UserToken();
                                    userToken.ApplicationUserId = user.Id;
                                    userToken.TokenId           = token.Id;
                                    _dbContext.UserToken.Add(userToken);
                                    _dbContext.SaveChanges();

                                    return(Json(new JsonResponse(true, "You have checked in!")));
                                }
                                else
                                {
                                    return(Json(new JsonResponse(false, "Duration of the token has expired.")));
                                }
                            }
                            else
                            {
                                return(Json(new JsonResponse(false, "You are too far away you cheater! You distance to kea is: " + distFromKEA)));
                            }
                        }
                        else
                        {
                            return(Json(new JsonResponse(false, "Student does not belong to this class.")));
                        }
                    }
                }
                return(Json(new JsonResponse(false, "Invalid login attempt.")));
            }
            var modelError = ModelState.Values.SelectMany(x => x.Errors).First().ErrorMessage;

            return(Json(new JsonResponse(false, modelError)));
        }
예제 #3
0
        public async Task <ActionResult> Logout([FromBody] StudentLoginModel model)
        {
            if (_accountService.Authenticate(model.Email, model.Password))
            {
                await _accountService.LogoutService(model.Email);

                return(Ok());
            }

            return(BadRequest());
        }
        public ActionResult Signin(StudentLoginModel login, string ReturnUrl = "")
        {
            string message = "";


            if (ModelState.IsValid)
            {
                var v = _unitOfWork.Student.GetEmail(login.StudentEmail);

                if (v != null)
                {
                    if (string.Compare(Crypto.Hash(login.StudentPassword), v.StudentPassword) == 0)
                    {
                        int    timeout   = login.RememberMe ? 525600 : 20;
                        var    ticket    = new FormsAuthenticationTicket(login.StudentEmail, login.RememberMe, timeout);
                        string encrypted = FormsAuthentication.Encrypt(ticket);

                        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted)
                        {
                            Expires  = DateTime.Now.AddMinutes(timeout),
                            HttpOnly = true
                        };

                        Response.Cookies.Add(cookie);

                        if (Url.IsLocalUrl(ReturnUrl))
                        {
                            return(Redirect(ReturnUrl));
                        }
                        else
                        {
                            return(RedirectToAction("UserHome", "Portal", new { id = v.StudentID }));
                        }
                    }
                    else
                    {
                        message = "Invalid Creditentials provided.";
                    }
                }
                else
                {
                    message = "Invalid creditential provided.";
                }


                ViewBag.Message = message;
                return(View());
            }

            return(View());
        }
예제 #5
0
        public async Task <IActionResult> Login(StudentLoginModel student, string tid)
        {
            if (ModelState.IsValid)
            {
                if (student.StuName == "terry" && student.Phone == "13412341234")
                {
                    var identity = new ClaimsIdentity(StudentAuthorizeAttribute.StudentAuthenticationScheme);
                    identity.AddClaim(new Claim(ClaimTypes.Name, student.StuName));
                    identity.AddClaim(new Claim(ClaimTypes.MobilePhone, student.Phone));
                    await HttpContext.SignInAsync(StudentAuthorizeAttribute.StudentAuthenticationScheme, new ClaimsPrincipal(identity));

                    return(RedirectToAction("ReportDetail", new { tid, rptid = Guid.NewGuid().ToString("N") }));
                }
            }
            return(View(student));
        }
예제 #6
0
        public async Task <ActionResult> Login([FromBody] StudentLoginModel model)
        {
            try
            {
                LoginRespond loginRespond = await _accountService.LoginServiceAsync(model);

                if (loginRespond.Pass)
                {
                    return(Ok(loginRespond));
                }
                else
                {
                    return(BadRequest(loginRespond));
                }
            }
            catch
            {
                return(BadRequest(model));
            }
        }
        public async Task <IActionResult> StudentLogin(StudentLoginModel model)
        {
            if (ModelState.IsValid)
            {
                Student student = await db.Students.FirstOrDefaultAsync(s => s.StudentId == model.StudentId);

                if (student != null && VerifyHashedPassword(student.Password, model.Password))
                {
                    if (HttpContext.Session.Keys.Contains("student"))
                    {
                        await LogoutWithoutRedirect();

                        HttpContext.Session.Remove("student");
                    }

                    await Authenticate(model.StudentId.ToString());

                    if (model.StudentId == 8080)
                    {
                        TempData.Put("admin4ik", new Admin {
                            AdminId = model.StudentId, Password = model.Password
                        });
                        return(RedirectToAction("Index", "Admin"));
                    }
                    else
                    {
                        TempData.Put("studentik", student);
                        if (student.Email != null)
                        {
                            // SendEmailAsync(student.Email, true).GetAwaiter();
                        }

                        return(RedirectToAction("Personal", "Student"));
                    }
                }

                ViewBag.ErrorMessage = "Incorrect StudentId or Password.";
            }

            return(View(model));
        }
예제 #8
0
        public async Task <ActionResult> Login(StudentLoginModel model)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(_baseAddress);

                client.DefaultRequestHeaders.Clear();

                var json = JsonConvert.SerializeObject(model);

                var data = new StringContent(json, Encoding.UTF8, "application/json");

                HttpResponseMessage Res = await client.PostAsync("Student/Authenticate", data);

                if (Res.IsSuccessStatusCode)
                {
                    var loginResponse = Res.Content.ReadAsStringAsync().Result;

                    StudentLoggedInModel student = JsonConvert.DeserializeObject <StudentLoggedInModel>(loginResponse);

                    //create user session
                    Session["UserID"]               = student.Id.ToString();
                    Session["UserEmail"]            = student.Email.ToString();
                    Session["UserFirstName"]        = student.FirstName.ToString();
                    Session["UserLastName"]         = student.LastName.ToString();
                    Session["UserPhoneNumber"]      = student.PhoneNumber.ToString();
                    Session["UserDateOfBirth"]      = student.DateOfBirth.ToString();
                    Session["UserEducationEndDate"] = student.EducationEndDate.ToString();
                    Session["UserNationality"]      = student.Nationality.ToString();
                    Session["UserToken"]            = student.Token.ToString();
                    return(RedirectToAction("UserDashBoard"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Wrong credentials");
                }
            }
            return(View(model));
        }
예제 #9
0
        //For login --helper
        //Generate token and update logs
        private async Task <LoginRespond> CheckInfoAsync(StudentLoginModel studentLogin, string passwordEncoded)
        {
            var user = _context.Users.SingleOrDefault(i => i.Email == studentLogin.Email);

            if (user.Password == passwordEncoded)
            {
                LoginLogger loginLogger = new LoginLogger
                {
                    Email        = studentLogin.Email,
                    Password     = passwordEncoded,
                    LoginSuccess = true,
                    Time         = DateTime.Now
                };
                _context.LoginLogs.Add(loginLogger);
                await _context.SaveChangesAsync();

                string token = Encoder(DateTime.Now.ToString());

                var  student    = _context.Students.SingleOrDefault(i => i.Email == studentLogin.Email);
                bool isAccepted = false;
                if (student != null)
                {
                    isAccepted = student.AdminPermition == true ? true : false;
                }

                LoginRespond loginRespond = new LoginRespond
                {
                    Pass       = true,
                    Email      = loginLogger.Email,
                    Token      = token,
                    LoginTime  = DateTime.Now,
                    IsAdmin    = user.UserRole == Role.Admin ? true : false,
                    IsAccepted = isAccepted
                };

                await AddTokenLog(loginLogger.Email, token, user.UserRole);

                user = null;

                return(loginRespond);
            }
            else
            {
                LoginLogger loginLogger = new LoginLogger
                {
                    Email        = studentLogin.Email,
                    Password     = passwordEncoded,
                    LoginSuccess = false,
                    Time         = DateTime.Now
                };
                _context.LoginLogs.Add(loginLogger);
                await _context.SaveChangesAsync();

                return(new LoginRespond
                {
                    Pass = false,
                    Email = studentLogin.Email,
                    LoginTime = DateTime.Now,
                    Token = "Login Failed"
                });
            }
        }