public user getCurrentUser()
        {
            IdentityHelper helper = new IdentityHelper();

            string currentDomain = Domain.GetCurrentDomain().Name;
            user currentUser = null;

            currentUser = new user();
            currentUser.lanID = HttpContext.Current.User.Identity.Name;
            currentUser.name = helper.GetUserDisplayName(HttpContext.Current.User.Identity.Name);

            return currentUser;
        }
Exemple #2
0
        private void CreateAndLoginUser()
        {
            if (!IsValid)
            {
                return;
            }
            var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();
            var user          = new ApplicationUser()
            {
                UserName = email.Text, Email = email.Text
            };
            IdentityResult result = manager.Create(user);

            if (result.Succeeded)
            {
                var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
                if (loginInfo == null)
                {
                    RedirectOnFail();
                    return;
                }
                result = manager.AddLogin(user.Id, loginInfo.Login);
                if (result.Succeeded)
                {
                    signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // var code = manager.GenerateEmailConfirmationToken(user.Id);
                    // Send this link via email: IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id)

                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    return;
                }
            }
            AddErrors(result);
        }
        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Validate the user password
                var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();

                // This doen't count login failures towards account lockout
                // To enable password failures to trigger lockout, change to shouldLockout: true
                var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

                switch (result)
                {
                case SignInStatus.Success:
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    break;

                case SignInStatus.LockedOut:
                    Response.Redirect("/Account/Lockout");
                    break;

                case SignInStatus.RequiresVerification:
                    Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
                                                    Request.QueryString["ReturnUrl"],
                                                    RememberMe.Checked),
                                      true);
                    break;

                case SignInStatus.Failure:
                default:
                    FailureText.Text     = "Invalid login attempt";
                    ErrorMessage.Visible = true;
                    break;
                }
            }
        }
Exemple #4
0
        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // 验证用户密码
                var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();

                // 这不会计入到为执行帐户锁定而统计的登录失败次数中
                // 若要在多次输入错误密码的情况下触发锁定,请更改为 shouldLockout: true
                var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

                switch (result)
                {
                case SignInStatus.Success:
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    break;

                case SignInStatus.LockedOut:
                    Response.Redirect("/Account/Lockout");
                    break;

                case SignInStatus.RequiresVerification:
                    Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
                                                    Request.QueryString["ReturnUrl"],
                                                    RememberMe.Checked),
                                      true);
                    break;

                case SignInStatus.Failure:
                default:
                    FailureText.Text     = "无效的登录尝试";
                    ErrorMessage.Visible = true;
                    break;
                }
            }
        }
Exemple #5
0
        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // 사용자 암호의 유효성을 검사합니다.
                var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();

                // 계정이 잠기는 로그인 실패로 간주되지 않습니다.
                // 암호 오류 시 잠금을 트리거하도록 설정하려면 shouldLockout: true로 변경하십시오.
                var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

                switch (result)
                {
                case SignInStatus.Success:
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    break;

                case SignInStatus.LockedOut:
                    Response.Redirect("/Account/Lockout");
                    break;

                case SignInStatus.RequiresVerification:
                    Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
                                                    Request.QueryString["ReturnUrl"],
                                                    RememberMe.Checked),
                                      true);
                    break;

                case SignInStatus.Failure:
                default:
                    FailureText.Text     = "잘못된 로그인 시도";
                    ErrorMessage.Visible = true;
                    break;
                }
            }
        }
        private void CreateAndLoginUser()
        {
            if (!IsValid)
            {
                return;
            }
            var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();
            var user          = new ApplicationUser()
            {
                UserName = email.Text, Email = email.Text
            };
            IdentityResult result = manager.Create(user);

            if (result.Succeeded)
            {
                var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
                if (loginInfo == null)
                {
                    RedirectOnFail();
                    return;
                }
                result = manager.AddLogin(user.Id, loginInfo.Login);
                if (result.Succeeded)
                {
                    signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);

                    // Para obtener más información sobre cómo habilitar la confirmación de cuentas y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771
                    // var code = manager.GenerateEmailConfirmationToken(user.Id);
                    // Enviar este vínculo por correo electrónico: IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id)

                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    return;
                }
            }
            AddErrors(result);
        }
        private void CreateAndLoginUser()
        {
            if (!IsValid)
            {
                return;
            }
            var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();
            var user          = new ApplicationUser()
            {
                UserName = email.Text, Email = email.Text
            };
            IdentityResult result = manager.Create(user);

            if (result.Succeeded)
            {
                var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
                if (loginInfo == null)
                {
                    RedirectOnFail();
                    return;
                }
                result = manager.AddLogin(user.Id, loginInfo.Login);
                if (result.Succeeded)
                {
                    signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);

                    // 有关如何启用帐户确认和密码重置的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=320771
                    // var code = manager.GenerateEmailConfirmationToken(user.Id);
                    // 发送包含此链接的电子邮件: IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id)

                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    return;
                }
            }
            AddErrors(result);
        }
Exemple #8
0
        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Valide a senha de usuário
                var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();

                // Isso não conta falhas de logon para bloqueio de conta
                // Para habilitar falhas de senha para acionar o bloqueio, mude para shouldLockout: true
                var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

                switch (result)
                {
                case SignInStatus.Success:
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    break;

                case SignInStatus.LockedOut:
                    Response.Redirect("/Account/Lockout");
                    break;

                case SignInStatus.RequiresVerification:
                    Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
                                                    Request.QueryString["ReturnUrl"],
                                                    RememberMe.Checked),
                                      true);
                    break;

                case SignInStatus.Failure:
                default:
                    FailureText.Text     = "Tentativa de logon inválida";
                    ErrorMessage.Visible = true;
                    break;
                }
            }
        }
Exemple #9
0
        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Validar la contraseña del usuario
                var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();

                // Esto no cuenta los errores de inicio de sesión hacia el bloqueo de cuenta
                // Para habilitar los errores de contraseña para desencadenar el bloqueo, cambie a shouldLockout: true
                var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);

                switch (result)
                {
                case SignInStatus.Success:
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    break;

                case SignInStatus.LockedOut:
                    Response.Redirect("/Account/Lockout");
                    break;

                case SignInStatus.RequiresVerification:
                    Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
                                                    Request.QueryString["ReturnUrl"],
                                                    RememberMe.Checked),
                                      true);
                    break;

                case SignInStatus.Failure:
                default:
                    FailureText.Text     = "Intento de inicio de sesión no válido";
                    ErrorMessage.Visible = true;
                    break;
                }
            }
        }
Exemple #10
0
        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Benutzerkennwort überprüfen
                var             manager = new ApplicationUserManager();
                ApplicationUser user    = manager.Find(UserName.Text, Password.Text);
                if (user != null)
                {
                    IdentityHelper.SignIn(manager, user, RememberMe.Checked);

                    BCM.WebFormsApplication.BLL.ShoppingCartActions usersShoppingCart = new BCM.WebFormsApplication.BLL.ShoppingCartActions();
                    String cartId = usersShoppingCart.GetCartId();
                    usersShoppingCart.MigrateCart(cartId, UserName.Text);

                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                }
                else
                {
                    FailureText.Text     = "Invalid username or password.";
                    ErrorMessage.Visible = true;
                }
            }
        }
Exemple #11
0
        public async Task <AppResponse> AtualizarCoordenador(AtualizarCoordenadorRequest request)
        {
            Coordenador coordenador = await _uow.Usuarios.ObterCoordenador(request.Id);

            if (coordenador == null)
            {
                return(new AppResponse(false, "Coordenador não encontrado."));
            }

            if (string.IsNullOrEmpty(request.Senha))
            {
                coordenador.Usuario.AdicionarErro("Informe a nova senha.");
            }

            if (string.IsNullOrEmpty(request.SenhaAntiga))
            {
                coordenador.Usuario.AdicionarErro("Informe a senha antiga.");
            }

            if (!coordenador.Usuario.TaValido())
            {
                return(new AppResponse(false, ERRO_BASE, coordenador.Usuario.ObterErros()));
            }

            coordenador.Atualizar(request);
            await _uow.CommitAsync();

            IdentityResult result = await _userManager.ChangePasswordAsync(coordenador.Usuario, request.SenhaAntiga, request.Senha);

            if (!result.Succeeded)
            {
                return(new AppResponse(MSG_ERRO_PWD_COORDENADOR, false, IdentityHelper.ObterErros(result)));
            }

            return(new AppResponse(true, MSG_UPDATE_SUCESSO, new CoordenadorDTO(coordenador)));
        }
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
            var signInManager = Context.GetOwinContext().Get <ApplicationSignInManager>();
            var user          = new User()
            {
                UserName = Email.Text, Email = Email.Text
            };
            IdentityResult result = manager.Create(user, Password.Text);

            if (result.Succeeded)
            {
                //string code = manager.GenerateEmailConfirmationToken(user.Id);
                //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
                //manager.SendEmail(user.Id, "Hesabınızı onaylayın", "Lütfen hesabınızı onaylamak için <a href=\"" + callbackUrl + "\">buraya tıklayın</a>.");

                signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
Exemple #13
0
        private void CreateAndLoginUser()
        {
            if (!IsValid)
            {
                return;
            }
            var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
            var user    = new ApplicationUser()
            {
                UserName = email.Text, Email = email.Text
            };
            IdentityResult result = manager.Create(user);

            if (result.Succeeded)
            {
                var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
                if (loginInfo == null)
                {
                    RedirectOnFail();
                    return;
                }
                result = manager.AddLogin(user.Id, loginInfo.Login);
                if (result.Succeeded)
                {
                    IdentityHelper.SignIn(manager, user, isPersistent: false);

                    // To enable account confirmation: see FWLINK:
                    var code = manager.GenerateEmailConfirmationToken(user.Id);
                    Response.Redirect(IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id.ToString()));

                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    return;
                }
            }
            AddErrors(result);
        }
        private void CreateAndLoginUser()
        {
            if (!IsValid)
            {
                return;
            }
            var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
            var user    = new ApplicationUser()
            {
                UserName = email.Text, Email = email.Text
            };
            IdentityResult result = manager.Create(user);

            if (result.Succeeded)
            {
                var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
                if (loginInfo == null)
                {
                    RedirectOnFail();
                    return;
                }
                result = manager.AddLogin(user.Id, loginInfo.Login);
                if (result.Succeeded)
                {
                    IdentityHelper.SignIn(manager, user, isPersistent: false);

                    // Pour plus d'informations sur l'activation de la confirmation du compte et la réinitialisation du mot de passe, consultez  http://go.microsoft.com/fwlink/?LinkID=320771
                    // var code = manager.GenerateEmailConfirmationToken(user.Id);
                    // Envoyer ce lien par e-mail : IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id)

                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    return;
                }
            }
            AddErrors(result);
        }
Exemple #15
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

            // Create roles here
            IServiceScope serviceProvider = app.ApplicationServices.GetRequiredService <IServiceProvider>().CreateScope(); //Dependency injection

            IdentityHelper.CreateRoles(serviceProvider.ServiceProvider, IdentityHelper.Instructor, IdentityHelper.Student).Wait();

            IdentityHelper.CreateDefaultInstructor(serviceProvider.ServiceProvider).Wait();
        }
Exemple #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string code   = IdentityHelper.GetCodeFromRequest(Request);
            string userId = IdentityHelper.GetUserIdFromRequest(Request);

            if (code != null && userId != null)
            {
                using (SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("insert into Users(UserId,FirstName,LastName,Gender) values " +
                                                    "(@id,null,null,null) ", con);
                    cmd.Parameters.AddWithValue("@id", userId);
                    cmd.ExecuteNonQuery();
                }

                var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var result  = manager.ConfirmEmail(userId, code);
                if (result.Succeeded)
                {
                    using (SqlConnection con = new SqlConnection(cs))
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("Insert into AspNetUserRoles (UserId,RoleId) values(@userid,'2')", con);
                        cmd.Parameters.AddWithValue("@userid", userId);
                        cmd.ExecuteNonQuery();
                    }


                    successPanel.Visible = true;
                    return;
                }
            }
            successPanel.Visible = false;
            errorPanel.Visible   = true;
        }
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            var manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
            var user    = new ApplicationUser()
            {
                UserName = Email.Text, Email = Email.Text
            };
            IdentityResult result = manager.Create(user, Password.Text);

            if (result.Succeeded)
            {
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                //string code = manager.GenerateEmailConfirmationToken(user.Id);
                //string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
                //manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");

                IdentityHelper.SignIn(manager, user, isPersistent: false);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                ErrorMessage.Text = result.Errors.FirstOrDefault();
            }
        }
        /// <summary>
        /// 添加系统信息
        /// </summary>
        /// <param name="systemAddDto"></param>
        /// <returns></returns>
        public int AddSystemInfo(SystemAddDto systemAddDto)
        {
            string Code;

            if (string.IsNullOrEmpty(systemAddDto.Code))
            {
                Code = IocUnity.Get <RepositorySystem>().GetNextSystemCode();
            }
            else
            {
                Code = systemAddDto.Code;
            }
            TSystem system = new TSystem
            {
                Id          = IdentityHelper.NewSequentialGuid().ToString("N"),
                Name        = systemAddDto.Name,
                EnglishName = systemAddDto.EnglishName,
                Instruction = systemAddDto.Instruction,
                LogoUrl     = systemAddDto.LogoUrl,
                Code        = Code
            };

            return(IocUnity.Get <RepositorySystem>().Insert(system));
        }
Exemple #19
0
        public async Task <ActionResult <Availability> > SaveAvailabilityAsync(AvailabilityViewModel availabilityViewModel)
        {
            if (availabilityViewModel == null)
            {
                return(BadRequest("No valid availability received"));
            }
            if (availabilityViewModel.ShiftId == Guid.Empty)
            {
                return(BadRequest("No valid shiftId received"));
            }
            if (availabilityViewModel.ParticipationId == Guid.Empty)
            {
                return(BadRequest("No valid participationId received"));
            }
            if (availabilityViewModel.Type == AvailibilityType.Scheduled)
            {
                return(BadRequest("Nice try, You cannot schedule yourself"));
            }

            try
            {
                Availability availability =
                    (await availabilityService.GetAvailability((Guid)availabilityViewModel.ParticipationId,
                                                               availabilityViewModel.ShiftId)).Data;
                if (availability != null)
                {
                    return(UnprocessableEntity(new ErrorViewModel
                    {
                        Type = Type.Error, Message = "Availability already exists"
                    }));
                }

                availability = AvailabilityViewModel.CreateAvailability(availabilityViewModel);
                if (availability == null)
                {
                    return(BadRequest("Unable to convert availabilityViewModel to Availability"));
                }

                if (availability.Participation == null || availability.Shift == null)
                {
                    return(BadRequest("Unable to add Participation and/of shift to Availability"));
                }

                availability.Participation = null;
                availability.Shift         = null;

                string oid = IdentityHelper.GetOid(HttpContext.User.Identity as ClaimsIdentity);
                availability.LastEditBy = oid;

                TaskResult <Availability> result;
                if (availability.Id == Guid.Empty)
                {
                    result = await availabilityService.AddAvailability(availability);
                }
                else
                {
                    return(BadRequest("Cannot update existing Availability with post method"));
                }

                if (!result.Succeeded)
                {
                    return(UnprocessableEntity(new ErrorViewModel {
                        Type = Type.Error, Message = result.Message
                    }));
                }
                return(Ok(AvailabilityViewModel.CreateVm(result.Data)));
            }
            catch (Exception ex)
            {
                string message = GetType().Name + "Error in " + nameof(SaveAvailabilityAsync);
                logger.LogError(ex, message);
                return(UnprocessableEntity(new ErrorViewModel {
                    Type = Type.Error, Message = message
                }));
            }
        }
 protected string GetManageUrl()
 {
     return(IdentityHelper.IsProxiadClient() ? "~/Account/ManageOpenId" : "~/Account/Manage");
 }
 protected string GetLoginLabel()
 {
     return(IdentityHelper.IsProxiadClient() ? "Log in with Office 365" : "Log in");
 }
        protected void CreateUser_Click(object sender, EventArgs e)


        {
            try
            {
                using (var cn = new SqlConnection(
                           ConfigurationManager.ConnectionStrings["Biblioteca"].ConnectionString))
                {
                    using (var cmd = new SqlCommand("PROC_INSERT_USUARIO", cn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@nome", nomeTextBox.Text);
                        cmd.Parameters.AddWithValue("@datanasc", datanascimentoTextBox.Text);
                        cmd.Parameters.AddWithValue("@rg", RG.Text);
                        cmd.Parameters.AddWithValue("@cpf", CPF.Text);
                        cmd.Parameters.AddWithValue("@email", Email.Text);
                        cmd.Parameters.AddWithValue("@senha", Password.Text);
                        cmd.Parameters.AddWithValue("@confirmacaosenha", ConfirmPassword.Text);

                        cn.Open();



                        cmd.ExecuteNonQuery();

                        var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                        var signInManager = Context.GetOwinContext().Get <ApplicationSignInManager>();
                        var user          = new ApplicationUser()
                        {
                            UserName = Email.Text, Email = Email.Text
                        };
                        IdentityResult result = manager.Create(user, Password.Text);

                        if (result.Succeeded)
                        {
                            IdentityResult createRoleResult = null;
                            var            roleManager      = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new ApplicationDbContext()));
                            if (!roleManager.RoleExists(Roles.Funcionario.ToString()))
                            {
                                createRoleResult = roleManager.Create(new IdentityRole(Roles.Funcionario.ToString()));
                            }
                            if (createRoleResult.Succeeded)
                            {
                                var addToRoleResult = manager.AddToRole(user.Id, Roles.Funcionario.ToString());
                            }


                            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                            string code        = manager.GenerateEmailConfirmationToken(user.Id);
                            string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
                            manager.SendEmail(user.Id, "Confirmação de conta", "Por favor, confirme sua conta clicando <a href=\"" + callbackUrl + "\">aqui</a>.");

                            if (user.EmailConfirmed)
                            {
                                var resultSignIn = signInManager.PasswordSignIn(Email.Text, Password.Text, false, shouldLockout: false);
                                SigninValidation(resultSignIn);
                            }
                            else
                            {
                                ErrorMessage.Text = "Um email foi enviado para sua conta. Por favor, veja o seu email e confirme sua conta para completar o processo de cadastro.";
                            }
                        }



                        else
                        {
                            ErrorMessage.Text = "Funcionário já existe!";
                        }



                        if (cn.State != ConnectionState.Closed)
                        {
                            cn.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 private bool GetIsSameUser(ClaimsPrincipal user, string userId)
 {
     return(IdentityHelper.GetUserId(user) == userId);
 }
 public PostsController(AzureBlobService azureBlobService, PostAdapter postAdapter, IdentityHelper identityHelper)
 {
     _azureBlobService = azureBlobService;
     _postAdapter      = postAdapter;
     _identityHelper   = identityHelper;
 }
 /// <summary>
 ///     创建一个新的单向事务
 /// </summary>
 /// <returns>返回新创建的单向事务</returns>
 /// <exception cref="ArgumentNullException">参数错误</exception>
 public MessageTransaction <BaseMessage> CreateOnewayTransaction()
 {
     return(_transactionManager.Create(IdentityHelper.CreateOneway(_channel.LocalEndPoint, _channel.ChannelType), _channel));
 }
        public RedPocket Push(UserAccount userAccount, Guid accountId, int cryptoId, decimal amount, int count, string userPIN, string pin, string message = "")
        {
            if (userAccount.L1VerifyStatus != Entities.Enums.VerifyStatus.Certified)
            {
                throw new CommonException(ReasonCode.NOT_VERIFY_LV1, Resources.EMNeedLV1Verfied);
            }

            if (amount <= 0 || cryptoId <= 0)
            {
                throw new CommonException(Argument_Error, MessageResources.InvalidDataFormat);
            }
            if (count <= 0)
            {
                throw new CommonException(Argument_Error, MessageResources.InvalidDataFormat);
            }

            if (count > MaxCount)
            {
                throw new CommonException(Argument_Error, string.Format(MessageResources.RedPocket_MaxCount, MaxCount));
            }

            if (!string.IsNullOrWhiteSpace(message) && message.Length > 46)
            {
                throw new CommonException(Argument_Error, MessageResources.RedPocket_MaxMessage);
            }

            SecurityVerify.Verify(new PinVerifier(), SystemPlatform.FiiiPay, accountId.ToString(), userPIN, pin);

            var cryptoDAC = new CryptocurrencyDAC();
            var priceDAC  = new PriceInfoDAC();

            var crypto = cryptoDAC.GetById(cryptoId);

            if (crypto == null)
            {
                throw new SystemErrorException();
            }

            if (!crypto.Status.HasFlag(Foundation.Entities.Enum.CryptoStatus.RedPocket) || crypto.Enable == 0)
            {
                throw new CommonException(ReasonCode.CURRENCY_FORBIDDEN, MessageResources.CurrencyForbidden);
            }

            var min = crypto.DecimalPlace == 8 ? 0.00000001M : crypto.DecimalPlace == 6 ? 0.000001M : 0.00000001M;

            var minAmount = count * min;

            if (amount < minAmount)
            {
                throw new CommonException(Push_MinAmount, string.Format(MessageResources.RedPocket_MinAmount, minAmount, crypto.Code));
            }

            var price = priceDAC.GetPriceByName("USD", crypto.Code);

            var max       = crypto.DecimalPlace == 8 ? 999999999.999999999M : crypto.DecimalPlace == 6 ? 999999999.999999M : 999999999.999999999M;
            var maxAmount = Math.Round(MaxAmount / price, crypto.DecimalPlace);

            if (count > 1)
            {
                maxAmount = Math.Round(MaxAmount * count / price, crypto.DecimalPlace);
            }

            if (amount >= max || Math.Round(amount, crypto.DecimalPlace) > maxAmount)
            {
                throw new CommonException(Argument_Error, string.Format(MessageResources.RedPocket_MaxAmount, maxAmount, crypto.Code));
            }

            var userWalletDAC          = new UserWalletDAC();
            var redPocketDAC           = new RedPocketDAC();
            var userWalletStatementDAC = new UserWalletStatementDAC();
            var userTransactionDAC     = new UserTransactionDAC();

            var wallet = userWalletDAC.GetByAccountId(accountId, cryptoId);

            if (wallet == null || wallet.Balance < amount)
            {
                throw new CommonException(ReasonCode.INSUFFICIENT_BALANCE, MessageResources.InsufficientBalance);
            }

            var fiatAmount = price * amount;

            using (var scope = new TransactionScope())
            {
                try
                {
                    var redPocket = new RedPocket
                    {
                        AccountId      = accountId,
                        Status         = RedPocketStatus.Actived,
                        PassCode       = GeneralPassCode(),
                        CryptoCode     = crypto.Code,
                        Amount         = amount,
                        Balance        = amount,
                        Count          = count,
                        RemainCount    = count,
                        Message        = message,
                        Timestamp      = DateTime.UtcNow,
                        ExpirationDate = DateTime.UtcNow.AddMinutes(_expried),
                        CryptoId       = cryptoId,
                        OrderNo        = IdentityHelper.OrderNo(),
                        FiatAmount     = fiatAmount <= 0 ? 0M : Math.Round(fiatAmount, 8)
                    };

                    var redPocketId = redPocketDAC.Insert(redPocket);
                    userTransactionDAC.Insert(new UserTransaction
                    {
                        Id         = Guid.NewGuid(),
                        AccountId  = accountId,
                        CryptoId   = redPocket.CryptoId,
                        CryptoCode = redPocket.CryptoCode,
                        Type       = UserTransactionType.PushRedPocket,
                        DetailId   = redPocketId.ToString(),
                        Status     = (byte)redPocket.Status,
                        Timestamp  = redPocket.Timestamp,
                        Amount     = redPocket.Amount,
                        OrderNo    = redPocket.OrderNo
                    });

                    userWalletDAC.Decrease(wallet.Id, amount);
                    userWalletStatementDAC.Insert(new UserWalletStatement
                    {
                        WalletId      = wallet.Id,
                        Balance       = wallet.Balance - amount,
                        Amount        = 0 - amount,
                        FrozenAmount  = 0,
                        FrozenBalance = wallet.FrozenBalance,
                        Action        = "Push Red Pocket",
                        Timestamp     = DateTime.UtcNow
                    });

                    QueueHelper.DelaySender.Send("FiiiPay_RedPocket", redPocketId);

                    scope.Complete();

                    return(redPocket);
                }
                catch (Exception ex)
                {
                    _log.Error(ex);

                    throw new SystemErrorException();
                }
            }
        }
        public RedPocketDetailOM Receive(UserAccount userAccount, string passcode, bool isZH = false)
        {
            if (userAccount == null)
            {
                throw new SystemErrorException();
            }

            if (string.IsNullOrWhiteSpace(passcode))
            {
                throw new CommonException(Argument_Error, MessageResources.InvalidDataFormat);
            }

            if (userAccount.L1VerifyStatus != Entities.Enums.VerifyStatus.Certified)
            {
                throw new CommonException(ReasonCode.NOT_VERIFY_LV1, Resources.EMNeedLV1Verfied);
            }

            var count = RedisHelper.StringGet(LockDbIndex, string.Format(KeyFormat, userAccount.Id));

            if (!string.IsNullOrWhiteSpace(count) && int.Parse(count) >= 10)
            {
                var ttl = RedisHelper.KeyTimeToLive(LockDbIndex, string.Format(KeyFormat, userAccount.Id));
                if (ttl != null)
                {
                    var message = "";
                    var t       = "";
                    try
                    {
                        t       = TimeConvert(ttl.Value, isZH);
                        message = string.Format(MessageResources.RedPocket_PassCodeErrorMaxCount, t);
                    }
                    catch (Exception exception)
                    {
                        _log.Error(exception.Message + "    " + MessageResources.RedPocket_PassCodeErrorMaxCount + "    " + t);
                    }

                    throw new CommonException(MaxError, message);
                }
            }

            var redPocketDAC = new RedPocketDAC();

            var redPocket = redPocketDAC.GetByPassCode(passcode);

            if (redPocket == null)
            {
                var errorCount = ErrorCount(userAccount.Id, count, isZH);
                throw new CommonException(PassCodeError, string.Format(MessageResources.RedPocket_PassCodeError, errorCount, 10 - errorCount));
            }

            if (redPocket.ExpirationDate < DateTime.UtcNow)
            {
                var errorCount = ErrorCount(userAccount.Id, count, isZH);
                throw new CommonException(PassCodeExpired, MessageResources.RedPocket_ReceiveExpired + Environment.NewLine + string.Format(MessageResources.RedPocket_PassCodeError, errorCount, 10 - errorCount));
            }

            var crypto = new CryptocurrencyDAC().GetByCode(redPocket.CryptoCode);

            if (!crypto.Status.HasFlag(Foundation.Entities.Enum.CryptoStatus.RedPocket) || crypto.Enable == 0)
            {
                throw new CommonException(ReasonCode.CURRENCY_FORBIDDEN, MessageResources.CurrencyForbidden);
            }

            var om = new RedPocketDetailOM();
            var redPocketReceiveDAC = new RedPocketReceiverDAC();

            var hasReceive = redPocketReceiveDAC.HasReceive(userAccount.Id, redPocket.Id);

            if (redPocket.Status == RedPocketStatus.Actived && hasReceive == null)
            {
                var userWalletDAC          = new UserWalletDAC();
                var userWalletStatementDAC = new UserWalletStatementDAC();
                var uwComponent            = new UserWalletComponent();
                var userTransactionDAC     = new UserTransactionDAC();

                var wallet = userWalletDAC.GetByCryptoCode(userAccount.Id, redPocket.CryptoCode);
                if (wallet == null)
                {
                    wallet = uwComponent.GenerateWallet(userAccount.Id, redPocket.CryptoCode);
                }

                var min = crypto.DecimalPlace == 8 ? 0.00000001M : crypto.DecimalPlace == 6 ? 0.000001M : 0.00000001M;
                var n   = crypto.DecimalPlace == 8 ? 100000000 : crypto.DecimalPlace == 6 ? 1000000 : 100000000;

                var amount = GetRandomMoney(redPocket, min, n);

                var priceDAC   = new PriceInfoDAC();
                var price      = priceDAC.GetPriceByName("USD", crypto.Code);
                var fiatAmount = price * amount;
                using (var scope = new TransactionScope())
                {
                    try
                    {
                        var redPocketReceiver = new RedPocketReceiver
                        {
                            PocketId      = redPocket.Id,
                            AccountId     = userAccount.Id,
                            SendAccountId = redPocket.AccountId,
                            CryptoCode    = redPocket.CryptoCode,
                            Amount        = amount,
                            Timestamp     = DateTime.UtcNow,
                            IsBestLuck    = redPocket.Count == 1,
                            OrderNo       = IdentityHelper.OrderNo(),
                            FiatAmount    = fiatAmount <= 0 ? 0M : Math.Round(fiatAmount, 8)
                        };
                        var id = redPocketReceiveDAC.Insert(redPocketReceiver);

                        userTransactionDAC.Insert(new UserTransaction
                        {
                            Id         = Guid.NewGuid(),
                            AccountId  = redPocketReceiver.AccountId,
                            CryptoId   = redPocket.CryptoId,
                            CryptoCode = redPocket.CryptoCode,
                            Type       = UserTransactionType.ReceiveRedPocket,
                            DetailId   = id.ToString(),
                            Status     = (byte)redPocket.Status,
                            Timestamp  = redPocketReceiver.Timestamp,
                            Amount     = redPocketReceiver.Amount,
                            OrderNo    = redPocketReceiver.OrderNo
                        });

                        userWalletDAC.Increase(wallet.Id, amount);
                        userWalletStatementDAC.Insert(new UserWalletStatement
                        {
                            WalletId      = wallet.Id,
                            Balance       = wallet.Balance + amount,
                            Amount        = amount,
                            FrozenAmount  = 0,
                            FrozenBalance = wallet.FrozenBalance,
                            Action        = "Receive Red Pocket",
                            Timestamp     = DateTime.UtcNow
                        });

                        redPocketDAC.UpdateRemain(redPocket.Id, amount);

                        if (redPocket.RemainCount == 0)
                        {
                            redPocketDAC.UpdateStatus(redPocket.Id, RedPocketStatus.Complate);
                            userTransactionDAC.UpdateStatus(UserTransactionType.PushRedPocket, redPocket.Id.ToString(), redPocket.AccountId, (byte)RedPocketStatus.Complate);

                            if (redPocket.Count > 1)
                            {
                                redPocketReceiveDAC.UpdateBestLuck(redPocket.Id);
                            }
                        }

                        scope.Complete();
                    }
                    catch (Exception ex)
                    {
                        _log.Error(ex);
                        throw new CommonException();
                    }
                }
                om.SelfAmount      = amount.ToString();
                om.ReceiveStatus   = ReceiveStatusEnum.Receive;
                om.HasExpried      = false;
                redPocket.Balance -= amount;
            }
            else
            {
                if (hasReceive != null)
                {
                    om.ReceiveStatus = ReceiveStatusEnum.HasReceive;
                    om.SelfAmount    = hasReceive.Amount.ToString();
                }
                else
                {
                    om.ReceiveStatus = ReceiveStatusEnum.None;
                    om.SelfAmount    = string.Empty;
                }
            }

            var account = new UserAccountComponent().GetById(redPocket.AccountId);

            om.Message        = redPocket.Message;
            om.SnederNickname = account.Nickname;

            om.TotalAmount   = redPocket.Amount.ToString();
            om.TotalCount    = redPocket.Count;
            om.CryptoCode    = redPocket.CryptoCode;
            om.ReceiveAmount = (redPocket.Amount - redPocket.Balance).ToString();
            om.ReceiveCount  = redPocket.Count - redPocket.RemainCount;
            om.Id            = redPocket.Id;
            om.HasExpried    = redPocket.ExpirationDate < DateTime.UtcNow;
            om.HasSelfSned   = redPocket.AccountId == userAccount.Id;

            return(om);
        }
Exemple #28
0
        public async Task <ActionResult <AvailabilityViewModel> > UpdateAvailabilityAsync(
            AvailabilityViewModel availabilityViewModel)
        {
            if (availabilityViewModel == null || availabilityViewModel.Id == Guid.Empty)
            {
                return(BadRequest("No valid availability received"));
            }
            if (availabilityViewModel.ShiftId == Guid.Empty)
            {
                return(BadRequest("No valid shiftId received"));
            }
            if (availabilityViewModel.ParticipationId == Guid.Empty)
            {
                return(BadRequest("No valid participationId received"));
            }
            if (availabilityViewModel.Type == AvailibilityType.Scheduled)
            {
                return(BadRequest("Nice try, You cannot schedule yourself"));
            }
            try
            {
                Availability availability = (await availabilityService.GetAvailability(availabilityViewModel.Id)).Data;
                if (availability == null)
                {
                    return(BadRequest("Unable to convert availabilityViewModel to Availability"));
                }
                if (availability.Type == AvailibilityType.Scheduled)
                {
                    return(BadRequest("Cannot modify availability when user is already scheduled"));
                }
                if (!availability.RowVersion.SequenceEqual(availabilityViewModel.RowVersion))
                {
                    return(BadRequest("Outdated entity received"));
                }

                availability.Preference = availabilityViewModel.Preference;
                availability.Type       = availabilityViewModel.Type;

                string oid = IdentityHelper.GetOid(HttpContext.User.Identity as ClaimsIdentity);
                availability.LastEditBy = oid;

                TaskResult <Availability> result = await availabilityService.UpdateAvailability(availability);

                if (!result.Succeeded)
                {
                    return(UnprocessableEntity(new ErrorViewModel {
                        Type = Type.Error, Message = result.Message
                    }));
                }
                AvailabilityViewModel vm = AvailabilityViewModel.CreateVm(result.Data);

                return(Ok(vm));
            }
            catch (Exception ex)
            {
                string message = GetType().Name + "Error in " + nameof(SaveAvailabilityAsync);
                logger.LogError(ex, message);
                return(UnprocessableEntity(new ErrorViewModel {
                    Type = Type.Error, Message = message
                }));
            }
        }
Exemple #29
0
 private static Mutex CreateMutexNotOwned(string pathName)
 {
     return(new Mutex(initiallyOwned: false, name: @"Global\" + IdentityHelper.GetStrongHashSuitableForObjectName(pathName)));
 }
Exemple #30
0
    protected void CreateUser_Click(object sender, EventArgs e)
    {
        var manager = new UserManager();
        var user    = new ApplicationUser()
        {
            UserName = UserName.Text
        };
        IdentityResult result = manager.Create(user, Password.Text);

        if (result.Succeeded)
        {
            IdentityHelper.SignIn(manager, user, isPersistent: false);
            Session["UserName"] = UserName.Text;
            Session["Password"] = Password.Text;
            Session["Type"]     = RadioButtonList1.SelectedValue;

            try
            {
                ServicePointManager.Expect100Continue      = true;
                ServicePointManager.SecurityProtocol       = (SecurityProtocolType)3072;
                ServicePointManager.DefaultConnectionLimit = 9999;

                var apiKey = "40ec1c94906389ccd7ec7e3a2781b00e-us17";
                var listId = "6c3f7acdc5";
                var email  = UserName.Text;

                using (var wc = new System.Net.WebClient())
                {
                    // Data to be posted to add email address to list
                    var data = new { email_address = email, status = "subscribed" };

                    // Serialize to JSON using Json.Net
                    var json = JsonConvert.SerializeObject(data);

                    // Base URL to MailChimp API
                    string apiUrl = "https://us17.api.mailchimp.com/3.0/";

                    // Construct URL to API endpoint being used
                    var url = string.Concat(apiUrl, "lists/", listId, "/members");

                    // Set content type
                    wc.Headers.Add("Content-Type", "application/json");

                    // Generate authorization header
                    string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(":" + apiKey));

                    // Set authorization header
                    wc.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);

                    // Post and get JSON response
                    //string result = wc.UploadString(url, json);


                    string myresult = wc.UploadString(url, json);
                    string ipAddress;
                    ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (ipAddress == "" || ipAddress == null)
                    {
                        ipAddress = Request.ServerVariables["REMOTE_ADDR"];
                    }


                    string urll = string.Format("http://freegeoip.net/json/{0}", ipAddress);
                    using (WebClient client = new WebClient())
                    {
                        string   jsonn    = client.DownloadString(urll);
                        Location location = new Location();
                        location = new JavaScriptSerializer().Deserialize <Location>(jsonn);
                        postcode = location.Zip_Code;
                    }

                    SqlDataSource1.InsertParameters.Add("postcode", "00");
                    SqlDataSource1.InsertParameters.Add("AdminApproval", "Active");
                    SqlDataSource1.InsertParameters.Add("IP", Request.UserHostAddress.ToString());
                    SqlDataSource1.Insert();

                    Response.Redirect("~/Account/ConfirmEmail.aspx");
                }
            }
            catch (Exception ex)
            {
                //ErrorMessage.Text = ex.Message;


                SqlDataSource1.InsertParameters.Add("postcode", "00");
                SqlDataSource1.InsertParameters.Add("AdminApproval", "Active");
                SqlDataSource1.InsertParameters.Add("IP", Request.UserHostAddress.ToString());
                SqlDataSource1.Insert();

                Response.Redirect("~/Account/ConfirmEmail.aspx");
            }



            //IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
        }
        else
        {
            ErrorMessage.Text = result.Errors.FirstOrDefault();
        }
    }
Exemple #31
0
        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Validate the user password
                var manager       = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager <ApplicationSignInManager>();

                // This doen't count login failures towards account lockout
                // To enable password failures to trigger lockout, change to shouldLockout: true


                // Database will reference these when they are called
                string emailAddress = Email.Text;
                string password     = Password.Text;

                // Connection to database and whether or not it will successfully access it
                string          connStr = "server=csdatabase.eku.edu;user=stu_csc440;database=csc440_db;port=3306;password=Maroons18;";
                MySqlConnection conn    = new MySql.Data.MySqlClient.MySqlConnection(connStr);
                try
                {
                    Console.WriteLine("Connecting to MySQL...");

                    conn.Open();

                    string sql = "SELECT userName FROM gitoutuser WHERE emailAdd=@eAddress and password=@pWord";

                    MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);

                    cmd.Parameters.AddWithValue("@eAddress", emailAddress);
                    cmd.Parameters.AddWithValue("@pWord", password);

                    MySqlDataReader myReader = cmd.ExecuteReader();

                    if (myReader.Read())
                    {
                        Email.Text    = myReader["userName"].ToString();
                        Password.Text = myReader["password"].ToString();
                    }
                    myReader.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                conn.Close();
                Console.WriteLine("Done.");

                // Puts the email and password in a varible so that it can check whether or not what was grabbed from the database is correct or not
                var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);
                switch (result)
                {
                case SignInStatus.Success:
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                    break;

                case SignInStatus.LockedOut:
                    Response.Redirect("/Account/Lockout");
                    break;

                case SignInStatus.RequiresVerification:
                    Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
                                                    Request.QueryString["ReturnUrl"],
                                                    RememberMe.Checked),
                                      true);
                    break;

                case SignInStatus.Failure:
                default:
                    FailureText.Text     = "Invalid login attempt";
                    ErrorMessage.Visible = true;
                    break;
                }
            }
        }
        public user getCurrentUser_WS(string lanId)
        {
            IdentityHelper helper = new IdentityHelper();

            string currentDomain = Domain.GetCurrentDomain().Name;
            user currentUser = null;

            currentUser = new user();
            currentUser.lanID = lanId;
            currentUser.name = helper.GetUserDisplayName(lanId);

            return currentUser;
        }