Ejemplo n.º 1
0
        public object Post(UpdateUserRegistrationPasswordRequest request)
        {
            var userAuthRepo = AuthRepo.AsUserAuthRepository(GetResolver());
            var existingUser = userAuthRepo.GetUserAuthByUserName(request.Email);

            if (existingUser == null)
            {
                var rs = new ResponseStatus {
                    Message = request.Email + " Not Found", ErrorCode = "404"
                };
                return(new UpdateUserRegistrationPasswordResponse {
                    ResponseStatus = rs
                });
            }

            var newUserAuth = existingUser;
            var updatedUser = userAuthRepo.UpdateUserAuth(existingUser, newUserAuth, request.NewPassword);

            return(new UpdateUserRegistrationPasswordResponse
            {
                DisplayName = updatedUser.DisplayName,
                UserId = updatedUser.Id.ToString(CultureInfo.InvariantCulture),
                ResponseStatus = new ResponseStatus {
                    Message = "200"
                }
            });
        }
        public async Task <IHttpActionResult> SendResetPasswordEmail(ForgetPasswordMailModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            try
            {
                GenericRepository <User> userRepo = unitOfWork.GetRepoInstance <User>();
                User user = userRepo.GetBy(u => u.Email.Equals(model.Email)).FirstOrDefault();
                if (null != user)
                {
                    // I must send a url with a form to reset the password
                    // I must get the token back with the email , password and confirm password
                    string originalToken = "";
                    string token         = "";
                    using (AuthRepo respository = new AuthRepo())
                    {
                        originalToken = await respository.GenerateResetPasswordToken(user.Id);

                        byte[] byt = System.Text.Encoding.UTF8.GetBytes(originalToken);
                        token = Convert.ToBase64String(byt);
                    }
                    //currentUser.EmailToken = token;
                    string url = GenerateURL(token, RESET_PASSWORD_PATH, null);
                    // Send Mail
                    string SenderEmail    = ConfigurationManager.AppSettings.Get("Email");
                    string SenderPassword = ConfigurationManager.AppSettings.Get("Password");
                    string SmtpHost       = ConfigurationManager.AppSettings.Get("SmtpHost");;
                    int    SmtpPort       = Convert.ToInt16(ConfigurationManager.AppSettings.Get("SmtpPort"));
                    bool   SmtpEnableSSL  = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("SmtpEnableSSL"));

                    string            Subject           = "Reset Enpire Account Password";
                    string            line1             = "Please ignore this e-mail if you didn't request to reset your password";
                    string            line2             = "Please follow the link beow to reset your account password!";
                    string            btnText           = "Reset Password";
                    string            Body              = GenerateEmailFromTemnplate(user.UserName, url, line1, line2, btnText);
                    MailConfiguration mailConfiguration = new MailConfiguration(SenderEmail, "Enpire Team", SenderPassword)
                    {
                        Host      = SmtpHost,
                        Port      = SmtpPort,
                        EnableSsl = SmtpEnableSSL
                    };
                    Email uEmail = new Email(mailConfiguration);
                    uEmail.Send(user.Email, Subject, Body);


                    return(Ok("Please check your email , you will find a link for reseting your password"));
                }
                else
                {
                    return(BadRequest("There is no account with the provided email , please check and try again."));
                }
            }
            catch (Exception e)
            {
                var ex = e;
            }
            return(null);
        }
Ejemplo n.º 3
0
        public void Login_Success_Test()
        {
            var authrepo   = new AuthRepo(usercontextmock.Object);
            var controller = new AuthController(config.Object, authrepo);
            var auth       = controller.Login(new User {
                UserId = 1, Username = "******", Password = "******"
            }) as OkObjectResult;

            Assert.AreEqual(200, auth.StatusCode);
        }
Ejemplo n.º 4
0
        public void Login_Failure_Test()
        {
            var authrepo   = new AuthRepo(usercontextmock.Object);
            var controller = new AuthController(config.Object, authrepo);
            var auth       = controller.Login(new User {
                UserId = 1, Username = "******", Password = "******"
            }) as OkObjectResult;

            Assert.IsNull(auth);
        }
Ejemplo n.º 5
0
        public async Task <JsonResult> OnPostAsync([FromBody] LoginVM loginVM)
        {
            dynamic jsonResponse = new JObject();

            if (ModelState.IsValid)
            {
                var result = await
                             _signInManager.PasswordSignInAsync(loginVM.Email.ToUpper(),
                                                                loginVM.Password, loginVM.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    AuthRepo loginRepo   = new AuthRepo(_signInManager, _config, _serviceProvider, _context);
                    var      UserManager = _serviceProvider
                                           .GetRequiredService <UserManager <IdentityUser> >();
                    var user = await UserManager.FindByEmailAsync(loginVM.Email);

                    if (user != null)
                    {
                        var sysuser     = _context.SystemUser.FirstOrDefault(u => u.Email == loginVM.Email);
                        var tokenString = loginRepo.GenerateJSONWebToken(user);

                        if (sysuser.Role == "Client")
                        {
                            jsonResponse.name = _context.Client.FirstOrDefault(c => c.UserId == sysuser.UserId).ClientName;
                        }
                        else if (sysuser.Role == "Labourer")
                        {
                            jsonResponse.name = _context.Labourer.FirstOrDefault(l => l.UserId == sysuser.UserId).LabourerFirstName
                                                + " " + _context.Labourer.FirstOrDefault(l => l.UserId == sysuser.UserId).LabourerLastName;
                        }
                        else if (sysuser.Role == "Administrator")
                        {
                            jsonResponse.name = "Admin";
                        }

                        jsonResponse.token  = tokenString;
                        jsonResponse.status = "OK";
                        jsonResponse.role   = sysuser.Role;
                        jsonResponse.email  = sysuser.Email;
                        jsonResponse.id     = loginRepo.GetIdByRole(sysuser.Email, sysuser.Role);
                        return(Json(jsonResponse));
                    }
                }
                else if (result.IsLockedOut)
                {
                    jsonResponse.token  = "";
                    jsonResponse.status = "Locked Out";
                    return(Json(jsonResponse));
                }
            }
            jsonResponse.token  = "";
            jsonResponse.status = "Invalid Login";
            return(Json(jsonResponse));
        }
Ejemplo n.º 6
0
 public AuthService(IConfiguration configuration, IEmailSender emailSender)
 //public AuthService(IConfiguration configuration)
 {
     config           = configuration;
     AuthRepo         = new AuthRepo(configuration);
     connectionString = Helper.ConnectionString(configuration);
     fn                = new Functions(connectionString);
     userlogRepo       = new UserLogsRepo(connectionString);
     SignUpSessionRepo = new SignUpSessionRepo(connectionString);
     _emailSender      = emailSender;
 }
Ejemplo n.º 7
0
        public async Task <JsonResult> OnPostAsync([FromBody] ClientRegisterVM input)
        {
            var user = new IdentityUser {
                UserName = input.User.Email.ToLower(), Email = input.User.Email
            };
            var result = await _userManager.CreateAsync(user, input.User.Password);

            var errorList = new List <string>();

            dynamic jsonResponse = new JObject();

            if (result.Succeeded)
            {
                SystemUser sysUser = new SystemUser()
                {
                    Email = input.User.Email,
                    Role  = "Client"
                };

                Client client = new Client
                {
                    ClientName        = input.Client.ClientName,
                    ClientEmail       = input.User.Email,
                    ClientPhoneNumber = input.Client.ClientPhoneNumber,
                    ClientCity        = input.Client.ClientCity,
                    ClientState       = input.Client.ClientState,
                    ClientDescription = input.Client.ClientDescription
                };
                _context.SystemUser.Add(sysUser);
                sysUser.Client.Add(client);
                _context.SaveChanges();

                AuthRepo registerRepo = new AuthRepo(_signInManager, _config, _serviceProvider, _context);
                var      tokenString  = registerRepo.GenerateJSONWebToken(user);
                jsonResponse.token  = tokenString;
                jsonResponse.status = "OK";
                jsonResponse.role   = "Client";
                jsonResponse.email  = sysUser.Email;
                jsonResponse.id     = client.ClientId;
                jsonResponse.name   = client.ClientName;
                return(Json(jsonResponse));
            }

            foreach (IdentityError error in result.Errors)
            {
                errorList.Add(error.Description);
            }

            jsonResponse.status      = 422;
            jsonResponse.description = errorList[0];
            jsonResponse.token       = "";
            return(Json(jsonResponse));
        }
        public FrmFingerprintLogin()
        {
            InitializeComponent();
            _repo = new AuthRepo();
            _staffFingerprints = _repo.GetStaffFingersForSignIn();

            comboScanner.Items.Clear();
            comboScanner.Items.Add("Digital Persona Scanner");
            comboScanner.SelectedIndex = 0;
            comboScanner.Enabled = true;

            this.ShowInTaskbar = false;
        }
Ejemplo n.º 9
0
        public static void Run([ServiceBusTrigger("passwords", Connection = "ServiceBusConnection")] string passwordChangeJson, TraceWriter log)
        {
            var authInfo = JsonConvert.DeserializeObject <AuthentincationInfo>(passwordChangeJson);

            log.Info($"C# Queue trigger function processed: {passwordChangeJson}");

            // store only the hash of the password
            authInfo.Password = authInfo.Password.ToSHA256Hash();

            var repo = new AuthRepo(ConnectionString, DatabaseName, CollectionName);

            repo.CreateAuthentication(authInfo);
        }
 public void generateJWT_invalidInput_tokenNotnull()
 {
     try
     {
         var mock = new Mock <IConfiguration>();
         mock.SetupGet(x => x[It.IsAny <string>()]).Returns(token_null);
         var res  = new AuthRepo(mock.Object);
         var data = res.GenerateJWT(user);
         Assert.IsNull(data);
     }
     catch (Exception e) {
         Assert.AreEqual("String reference not set to an instance of a String. (Parameter 's')", e.Message);
     }
 }
Ejemplo n.º 11
0
        private void loginBtn_Click(object sender, EventArgs e)
        {
            var user = AuthRepo.Authentication(loginTxtBox.Text, pswdTxtBox.Text);

            if (user == null)
            {
                MessageBox.Show("Неверный логин\\пароль", "Ошибка");
            }
            else
            {
                Hide();
                var mainForm = new MainForm(user);
                mainForm.Closed += (s, args) => this.Close();
                mainForm.Show();
            }
        }
Ejemplo n.º 12
0
        public IActionResult Login([FromBody] LoginData login)
        {
            if (login?.Email == null || login?.Password == null)
            {
                return(BadRequest("Password and/or email is missing."));
            }

            logger.LogInformation("login request {0}", login.Email);

            var authConfiguration = configuration.GetSection("AuthDbConnection");

            // TODO DI
            var repo = new AuthRepo(
                authConfiguration.GetValue <string>("ConnectionString"),
                authConfiguration.GetValue <string>("DbName"),
                authConfiguration.GetValue <string>("CollectionName"));

            var auth         = repo.GetAuthentication(login.Email);
            var passwordHash = login.Password.ToSHA256Hash();

            if (auth == null ||
                auth.Password?.Equals(passwordHash, StringComparison.InvariantCulture) == false ||
                auth.Email?.Equals(login.Email, StringComparison.InvariantCultureIgnoreCase) == false)
            {
                logger.LogInformation("login failed {0}", login.Email);
                return(Unauthorized());
            }

            var keyparts = configuration.GetSection("Secrets:RSA-PrivateKey").GetChildren().Select(c => c.Value);

            var privateKey     = string.Join(Environment.NewLine, keyparts);
            var jwtHelpert     = new JwtHelper(privateKey);
            var payload        = jwtHelpert.CreatePayload(auth);
            var jwtBearerToken = payload.CreateToken();

            // uncomment if you want to return the token as http only cookie
            // HttpContext.Response.Cookies.Append("SESSIONID", jwtBearerToken, new CookieOptions() { HttpOnly = true, Secure = true });
            logger.LogInformation("login success {0}", login.Email);
            return(Created("", new {
                token = jwtBearerToken,
                // additional data so that client does not need to decode those from the token
                payload.expiresAt,
                userId = auth.UserId
            }));
        }
Ejemplo n.º 13
0
        public object Put(UserRegistrationRequest request)
        {
            /*
             * if (HostContext.GlobalRequestFilters == null
             || !HostContext.GlobalRequestFilters.Contains(ValidationFilters.RequestFilter))
             ||{
             || UserRegistrationRequestValidator.ValidateAndThrow(request, ApplyTo.Put);
             ||}
             ||
             ||if (ValidateFn != null)
             ||{
             || var response = ValidateFn(this, HttpMethods.Put, request);
             || if (response != null)
             ||     return response;
             ||}*/

            var userAuthRepo = AuthRepo.AsUserAuthRepository(GetResolver());
            var session      = this.GetSession();

            var existingUser = userAuthRepo.GetUserAuth(session, null);

            if (existingUser == null)
            {
                throw HttpError.NotFound("User does not exist");
            }

            var newUserAuth = ToUserAuth(request);

            if (string.IsNullOrEmpty(newUserAuth.Email))
            {
                newUserAuth.Email = existingUser.Email;
            }
            if (string.IsNullOrEmpty(newUserAuth.DisplayName))
            {
                newUserAuth.DisplayName = newUserAuth.Email;
            }

            userAuthRepo.UpdateUserAuth(existingUser, newUserAuth, request.Password);

            return(new UserRegistrationResponse
            {
                UserId = existingUser.Id.ToString(CultureInfo.InvariantCulture),
            });
        }
Ejemplo n.º 14
0
        public JsonResult LoginAction(Repos.Models.LoginModel uDetails)
        {
            try
            {
                // TODO: Add delete logic here
                //return RedirectToAction("Login");

                AuthRepo _repo      = new AuthRepo();
                var      ResultData = _repo.GetUserAuthincate(uDetails);
                if (ResultData != null)
                {
                    Session["UserObj"] = ResultData;
                    var data = new
                    {
                        IsSuccess = true,
                        IsActive  = ResultData.UserStatus,
                        IsAdmin   = ResultData.IsAdmin
                    };
                    return(Json(data));
                }
                else
                {
                    var data = new
                    {
                        IsSuccess    = false,
                        ErrorMessage = "No user Found"
                    };
                    return(Json(data));
                }
            }
            catch (Exception ex)
            {
                var data = new
                {
                    IsSuccess    = false,
                    ErrorMessage = ex.Message.ToString()
                };
                return(Json(data));
            }
            // return Json(true);
        }
        public async Task <IHttpActionResult> ForgetPassword(ForgetPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            byte[] byt   = Convert.FromBase64String(model.Token);
            string token = System.Text.Encoding.UTF8.GetString(byt);

            using (AuthRepo repository = new AuthRepo())
            {
                IdentityResult result = await repository.ResetPassword(token, model.Email, model.NewPassword);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
                return(Ok());
            }
        }
Ejemplo n.º 16
0
        public IActionResult Login([FromBody] PensionCredentials login)
        {
            AuthRepo auth_repo = new AuthRepo(_config, repo);

            _log4net.Info("Login initiated!");
            IActionResult response = Unauthorized();
            //login.FullName = "user1";
            var user = auth_repo.AuthenticateUser(login);

            if (user == null)
            {
                return(NotFound());
            }
            else
            {
                var tokenString = auth_repo.GenerateJSONWebToken(user);
                response = Ok(new { token = tokenString });
            }

            return(response);
        }
        public HttpResponseMessage ConfirmEmail(string token)
        {
            var response = Request.CreateResponse();

            response.StatusCode = HttpStatusCode.Moved;
            using (var repository = new AuthRepo())
            {
                bool result = repository.ConfirmEmail(token);
                switch (result)
                {
                case true:
                    response.Headers.Location = new Uri(SUCCESS_REDIRECT);
                    return(response);

                case false:
                    response.Headers.Location = new Uri(FAIL_REDIRECT);
                    return(response);
                }
            }
            response.Headers.Location = new Uri(FAIL_REDIRECT);
            return(response);
        }
Ejemplo n.º 18
0
        public FrmLogin(bool showSplash = true)
        {
            if (showSplash)
            {
                var t = new Thread(new ThreadStart(ShowSplashScreen));
                t.Start();
                Thread.Sleep(5000);
                InitializeComponent();
                t.Abort();
            }
            else
            {
                InitializeComponent();
            }

            this.BringToFront();
            //this.Show();
            _authRepo = new AuthRepo();

            lblTitle.Text      = ApplicationSetting.ApplicationName;
            lblTitle.ForeColor = ApplicationSetting.PrimaryColor;
            btnLogin.BackColor = ApplicationSetting.PrimaryColor;

            lblLogin.ForeColor           = ApplicationSetting.SecondaryColor;
            lblEmail.ForeColor           = ApplicationSetting.SecondaryColor;
            lblPassword.ForeColor        = ApplicationSetting.SecondaryColor;
            lnkFingerprint.LinkColor     = ApplicationSetting.SecondaryColor;
            linkForgotPassword.LinkColor = ApplicationSetting.SecondaryColor;

            using (MemoryStream ms = new MemoryStream(ApplicationSetting.LogoBytes))
            {
                pictureBox1.Image = Image.FromStream(ms);
            }

            GetRemoteServerConnectionState();
            // Helper.GetEnumValuesAndDescriptions<ReportType>();
        }
Ejemplo n.º 19
0
 public FrmLogin()
 {
     InitializeComponent();
     MaterialSkinBase.InitializeForm(this);
     _authRepo = new AuthRepo();
 }
Ejemplo n.º 20
0
        /// <summary>
        ///     Create new Registration
        /// </summary>
        public object Post(UserRegistrationRequest request)
        {
            if (HostContext.GlobalRequestFilters == null ||
                !HostContext.GlobalRequestFilters.Contains(ValidationFilters.RequestFilter))    //Already gets run
            {
                if (UserRegistrationRequestValidator != null)
                {
                    UserRegistrationRequestValidator.ValidateAndThrow(request, ApplyTo.Post);
                }
            }

            var userAuthRepo = AuthRepo.AsUserAuthRepository(GetResolver());

            if (ValidateFn != null)
            {
                var validateResponse = ValidateFn(this, HttpMethods.Post, request);
                if (validateResponse != null)
                {
                    return(validateResponse);
                }
            }

            if (string.IsNullOrEmpty(request.DisplayName))
            {
                request.DisplayName = request.Email;
            }

            UserRegistrationResponse response = null;
            var session      = this.GetSession();
            var newUserAuth  = ToUserAuth(request);
            var existingUser = userAuthRepo.GetUserAuth(session, null);

            var registerNewUser = existingUser == null;
            var user            = registerNewUser
                ? userAuthRepo.CreateUserAuth(newUserAuth, request.Password)
                : userAuthRepo.UpdateUserAuth(existingUser, newUserAuth, request.Password);

            if (request.AutoLogin.GetValueOrDefault())
            {
                using (var authService = base.ResolveService <AuthenticateService>())
                {
                    var authResponse = authService.Post(
                        new Authenticate
                    {
                        provider = "credentials",
                        UserName = request.UserName ?? request.Email,
                        Password = request.Password,
                        Continue = request.Continue
                    });

                    if (authResponse is IHttpError)
                    {
                        throw (Exception)authResponse;
                    }

                    var typedResponse = authResponse as AuthenticateResponse;
                    if (typedResponse != null)
                    {
                        response = new UserRegistrationResponse
                        {
                            SessionId   = typedResponse.SessionId,
                            DisplayName = typedResponse.DisplayName,
                            ReferrerUrl = typedResponse.ReferrerUrl,
                            UserId      = user.Id.ToString(CultureInfo.InvariantCulture),
                        };
                    }
                }
            }

            if (registerNewUser)
            {
                session = this.GetSession();
                session.OnRegistered(this);
            }

            if (response == null)
            {
                response = new UserRegistrationResponse
                {
                    UserId      = user.Id.ToString(CultureInfo.InvariantCulture),
                    ReferrerUrl = request.Continue
                };
            }

            var isHtml = Request.ResponseContentType.MatchesContentType(MimeTypes.Html);

            if (isHtml)
            {
                if (string.IsNullOrEmpty(request.Continue))
                {
                    return(response);
                }

                return(new HttpResult(response)
                {
                    Location = request.Continue
                });
            }

            return(response);
        }
        public async Task <IHttpActionResult> Register(RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var repository = new AuthRepo())
            {
                string token = Cryptography.GetRandomKey(64);
                model.EmailToken = token;
                User user = new User()
                {
                    UserName       = model.UserName,
                    Email          = model.Email,
                    Company        = model.Company,
                    Position       = model.Position,
                    Country        = model.Country,
                    FirstName      = model.FirstName,
                    LastName       = model.LastName,
                    IsDeleted      = false,
                    EmailConfirmed = false,
                    EmailToken     = model.EmailToken,
                    isActive       = true,
                    RegisterDate   = DateTime.Now
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
                try
                {
                    UserManager.AddToRole(user.Id, "FreeUser");
                } catch (Exception e)
                {
                    var            a      = e.Message;
                    IdentityResult newRes = new IdentityResult("Something wrong happened,Please retry");
                    return(GetErrorResult(newRes));
                }

                string url = GenerateURL(token, CONFIRM_EMAIL_PATH, 1);

                // Send Mail
                string            SenderEmail       = ConfigurationManager.AppSettings.Get("Email");
                string            SenderPassword    = ConfigurationManager.AppSettings.Get("Password");
                string            SmtpHost          = ConfigurationManager.AppSettings.Get("SmtpHost");;
                int               SmtpPort          = Convert.ToInt16(ConfigurationManager.AppSettings.Get("SmtpPort"));
                bool              SmtpEnableSSL     = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("SmtpEnableSSL"));
                string            Subject           = "Enpire Account Created Successfully";
                string            line1             = "Thank you for signing up in Gap-Tech Pinch Analysis Tool";
                string            line2             = "Please follow the link beow to activate your account!";
                string            btnText           = "Activate Account";
                string            Body              = GenerateEmailFromTemnplate(user.UserName, url, line1, line2, btnText);
                MailConfiguration mailConfiguration = new MailConfiguration(SenderEmail, "Enpire Team", SenderPassword)
                {
                    Host      = SmtpHost,
                    Port      = SmtpPort,
                    EnableSsl = SmtpEnableSSL
                };
                Email uEmail = new Email(mailConfiguration);
                uEmail.Send(model.Email, Subject, Body);
                return(Ok());
            }
        }
 public FrmChangePassword(string userEmail)
 {
     InitializeComponent();
     _repo = new AuthRepo();
     _id   = userEmail;
 }
Ejemplo n.º 23
0
 public FrmPasswordReset()
 {
     InitializeComponent();
     _repo = new AuthRepo();
 }
Ejemplo n.º 24
0
        public object Post(CreateUser request)
        {
            if (HostContext.GetPlugin <AuthFeature>()?.SaveUserNamesInLowerCase == true)
            {
                if (request.UserName != null)
                {
                    request.UserName = request.UserName.ToLower();
                }
                if (request.Email != null)
                {
                    request.Email = request.Email.ToLower();
                }
            }

            CreateUserDataReponse response = null;

            var newUserAuth = ToUserAuth(AuthRepo, request);
            var user        = AuthRepo.CreateUserAuth(newUserAuth, request.Password);

            if (!request.Role.IsNullOrEmpty())
            {
                using (var assignRoleService = ResolveService <AssignRolesService>())
                {
                    var assignRoleResponse = assignRoleService.Post(new AssignRoles()
                    {
                        UserName = user.UserName,
                        Roles    = new List <string>()
                        {
                            request.Role
                        }
                    });
                    switch (assignRoleResponse)
                    {
                    case IHttpError _:
                        throw (Exception)assignRoleResponse;

                    default:
                        break;
                    }
                }
            }

            if (request.AutoLogin.GetValueOrDefault())
            {
                using (var authService = ResolveService <AuthenticateService>())
                {
                    var authResponse = authService.Post(
                        new Authenticate {
                        provider = CredentialsAuthProvider.Name,
                        UserName = request.UserName ?? request.Email,
                        Password = request.Password,
                        Continue = request.Continue
                    });

                    switch (authResponse)
                    {
                    case IHttpError _:
                        throw (Exception)authResponse;

                    case AuthenticateResponse typedResponse:
                        response = new CreateUserDataReponse
                        {
                            SessionId    = typedResponse.SessionId,
                            UserName     = typedResponse.UserName,
                            ReferrerUrl  = typedResponse.ReferrerUrl,
                            UserId       = user.Id.ToString(CultureInfo.InvariantCulture),
                            BearerToken  = typedResponse.BearerToken,
                            RefreshToken = typedResponse.RefreshToken,
                        };
                        break;
                    }
                }
            }

            var session = GetSession();

            if (!request.AutoLogin.GetValueOrDefault())
            {
                session.PopulateSession(user, new List <IAuthTokens>());
            }

            session.OnRegistered(Request, session, this);

            AuthEvents?.OnRegistered(Request, session, this);
            if (response == null)
            {
                response = new CreateUserDataReponse
                {
                    UserId      = user.Id.ToString(CultureInfo.InvariantCulture),
                    ReferrerUrl = request.Continue,
                    UserName    = session.UserName,
                };
            }

            var isHtml = Request.ResponseContentType.MatchesContentType(MimeTypes.Html);

            if (!isHtml)
            {
                return new CreateUserReponse()
                       {
                           Status = (int)CommonStatus.Success,
                           Data   = response
                       }
            }
            ;
            if (string.IsNullOrEmpty(request.Continue))
            {
                return(response);
            }

            return(new HttpResult(response)
            {
                Location = request.Continue
            });
        }
Ejemplo n.º 25
0
 public FrmResetPassword(string userEmail)
 {
     InitializeComponent();
     _repo         = new AuthRepo();
     txtEmail.Text = userEmail;
 }
        public async Task <JsonResult> OnPostAsync([FromBody] LabourerRegisterVM input)
        {
            var user = new IdentityUser {
                UserName = input.User.Email.ToLower(), Email = input.User.Email
            };
            var result = await _userManager.CreateAsync(user, input.User.Password);

            var errorList = new List <string>();

            dynamic jsonResponse = new JObject();

            if (result.Succeeded)
            {
                SystemUser sysUser = new SystemUser()
                {
                    Email = input.User.Email,
                    Role  = "Labourer"
                };

                Labourer labourer = new Labourer
                {
                    LabourerFirstName = input.Labourer.LabourerFirstName,
                    LabourerLastName  = input.Labourer.LabourerLastName,
                    LabourerSin       = input.Labourer.LabourerSin,
                    LabourerEmail     = input.User.Email,
                    IsAvailable       = true,
                    OnLeave           = false
                };
                _context.SystemUser.Add(sysUser);
                sysUser.Labourer.Add(labourer);
                _context.SaveChanges();

                //if (input.AvailableDays != null)
                //{

                //    foreach (string day in input.AvailableDays)
                //    {
                //        Availability availability = _context.Availability.Where(a => a.AvailabilityDay == day).FirstOrDefault();

                //        AvailabilityLabourer availabilityLabourer = new AvailabilityLabourer
                //        {
                //            AvailabilityId = availability.AvailabilityId,
                //            LabourerId = labourer.LabourerId
                //        };
                //        _context.AvailabilityLabourer.Add(availabilityLabourer);
                //        _context.SaveChanges();
                //    }
                //}
                //else
                //{
                //    await _userManager.DeleteAsync(user);
                //    _context.Labourer.Remove(labourer);
                //    _context.SystemUser.Remove(sysUser);
                //    _context.SaveChanges();
                //    jsonResponse.status = "Available day is not valid";
                //    jsonResponse.token = " ";
                //    return Json(jsonResponse);
                //}


                foreach (int skillId in input.Skills)
                {
                    LabourerSkill labourerSkill = new LabourerSkill
                    {
                        SkillId    = skillId,
                        LabourerId = labourer.LabourerId
                    };
                    _context.LabourerSkill.Add(labourerSkill);
                    _context.SaveChanges();
                }

                AuthRepo registerRepo = new AuthRepo(_signInManager, _config, _serviceProvider, _context);
                var      tokenString  = registerRepo.GenerateJSONWebToken(user);
                jsonResponse.token  = tokenString;
                jsonResponse.status = "OK";
                jsonResponse.role   = "Labourer";
                jsonResponse.email  = sysUser.Email;
                jsonResponse.id     = labourer.LabourerId;
                jsonResponse.name   = labourer.LabourerFirstName + ' ' + labourer.LabourerLastName;
                return(Json(jsonResponse));
            }

            foreach (IdentityError error in result.Errors)
            {
                errorList.Add(error.Description);
            }
            jsonResponse.status      = 422;
            jsonResponse.description = errorList[0];
            jsonResponse.token       = "";
            return(Json(jsonResponse));
        }