public static bool ExistsAccount(string username) { using (var db = new DBLogin()) { return(db.Account.FirstOrDefault(a => a.Username == username.ToUpper()) != null); } }
private Boolean CreateSysUser() { const String sysUser = "******"; const String sysPass = "******"; txtProcessInfo.Text += Environment.NewLine + "Criando usuário para uso do sistema..."; const String creationFail = "Falha ao criar usuário para o sistema. "; try { // Cria o usuário que será utilizado pelo sistema para execução de procedures String creationQuery; if (sqlVersion > 8) // SQL Server 2005 ou superior { creationQuery = "CREATE LOGIN " + sysUser + " WITH PASSWORD = '******'"; } else { creationQuery = "sp_addlogin '" + sysUser + "', '" + sysPass + "'"; } DBQuery dbQuery = new DBQuery(creationQuery, sqlConnection); dbQuery.Execute(false); } catch (Exception exc) { txtProcessInfo.Text += Environment.NewLine + creationFail + Environment.NewLine + exc.Message; return(false); } // Se não houve nenhuma falha armazena o usuário e retorna status de sucesso sysLogin = new DBLogin(sysUser, sysPass); return(true); }
public void BeforeEachTestInitialize() { loginService = new LoginService(); dbLogin = new DBLogin(); userService = new UserService(); userController = new UserController(); }
public void CleanUp() { loginService = null; dbLogin = null; //loginController = null; //login = null; }
public ActionResult Index(AppLogin login) { if (this.ModelState.IsValid) { DBLoginRepository loginRepository = new DBLoginRepository(this.DatabaseContext); DBEditorRepository editorRepository = new DBEditorRepository(this.DatabaseContext); DBEditor editor = editorRepository.Find(login.Username); if (editor != null && login.Username == editor.Username && PasswordHasher.Hash(login.Password, editor.PasswordSalt) == editor.PasswordHash) { DBLogin dBLogin = new DBLogin() { IDEditor = editor.ID, UserAgent = Request.UserAgent, UserIP = IPObtainer.GetIP(), UTCLogoutTime = DateTime.UtcNow.AddMinutes(10) }; loginRepository.Add(dBLogin, true); this.Session["authorized"] = dBLogin; return(RedirectToAction("Index", "Admin")); } else { return(View()); //neexistuje nebo nesedí přihlašovací údaje } } return(View()); }
public static SRP GetAccountSecurity(string username) { using (var db = new DBLogin()) { var acc = db.Account.FirstOrDefault(a => a.Username == username); return(new SRP(acc.Username, acc.SRPSalt.ToPositiveBigInteger(), acc.SRPVerifier.ToPositiveBigInteger())); } }
public static byte[] GetSessionKey(string username) { using (var db = new DBLogin()) return(db.Account .LoadWith(a => a.Session) .FirstOrDefault(a => a.Username == username) .Session.SessionKey); }
private void BindData(DBLogin Model) { txtDataBaseName.Text = Model.DataName; txtUserName.Text = Model.UserName; txtPassword.Text = Model.PassWord; txtPort.Text = Model.Port; ckbRember.Checked = (Model.IsRead == 1); }
internal void ReauthorizeLogin(HttpSessionStateBase httpSession) { DBLoginRepository loginRepository = new DBLoginRepository(this.DatabaseContext); DBLogin login = loginRepository.Find((httpSession["authorized"] as DBLogin).ID); login.UTCLogoutTime = DateTime.UtcNow.AddMinutes(10); loginRepository.Update(login, true); httpSession["authorized"] = login; }
public async Task <ApiResult <UserLoginCookie> > Login(string username, string password) { ApiResult <UserLoginCookie> apiresult = new ApiResult <UserLoginCookie>(); if (this.UserContext != null) { return(apiresult.Failure("You are all ready logged in. Logout before you can login.")); } if (String.IsNullOrWhiteSpace(username) || String.IsNullOrWhiteSpace(password)) { return(apiresult.Failure("Invalid Username/Password")); } DBAccount dbAccount = null; try { dbAccount = await WebAppContext.Factory.AccountManager.GetAccount(0, username).ConfigureAwait(false); } catch (Exception ex) { return(apiresult.Failure(ex)); } if (dbAccount == null) { return(apiresult.Failure("Account does not exist.")); } if (!HashUtils.VerifyHashMatch256(password, dbAccount.Salt, dbAccount.PasswordHash)) { return(apiresult.Failure("Invalid Password")); } DBLogin dbLogin = null; try { dbLogin = await DBLogin.LoginUserNameAsync(WebAppContext.Factory, dbAccount.UserName).ConfigureAwait(false); } catch (Exception ex) { return(apiresult.Failure(ex)); } if (dbLogin == null) { apiresult.Failure("Login Failed"); } apiresult.Success(new UserLoginCookie() { UserName = username, APIKey = dbLogin.APIKey, VerifyDate = dbLogin.LoginDate }); try { var ctx = await UserContext.InitContextFromCookie(this.HttpContext, apiresult.Result).ConfigureAwait(false); if (ctx == null) { return(apiresult.Failure("Failed to set login cookie for unknown reason.")); } } catch (Exception ex) { return(apiresult.Failure(ex)); } return(apiresult); }
public static void LoginDB(DB db, LoginResponse response, string username, string roles, string ip4) { // We now create an account with an empty password and the specified roles. // Note that it is not possible to log into an account with an empty password // using the normal login procedure. DBPerson open_person = null; using (IDbCommand cmd = db.CreateCommand()) { cmd.CommandText = @"SELECT * FROM Person WHERE login = @login;"; DB.CreateParameter(cmd, "login", username); using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { open_person = new DBPerson(reader); } } } if (open_person == null) { open_person = new DBPerson(); open_person.login = username; open_person.roles = roles; open_person.Save(db); } else { // only save if something has changed if (open_person.roles != roles) { open_person.roles = roles; open_person.Save(db); } } WebServiceLogin login = new WebServiceLogin(); login.Ip4 = ip4; login.User = open_person.login; db.Audit(login, "DBLogin_Extensions.Login (username: {0}, ip4: {1})", username, ip4); var result = new DBLogin(); result.person_id = open_person.id; result.ip4 = ip4; result.cookie = CreateCookie(); result.expires = DateTime.Now.AddDays(1); result.Save(db); response.User = username; response.UserName = username; response.UserRoles = open_person.Roles; response.Cookie = result.cookie; }
public static void SaveUserLogin(DBLogin login) { using (ApplicationContext db = new ApplicationContext()) { DBLogin lgn = db.Logins .FirstOrDefault(x => x.Login == login.Login); lgn = login; db.SaveChanges(); } }
/// <summary> /// 修改密码 /// </summary> /// <returns></returns> private Hashtable ChangePwd(HttpContext context) { Hashtable htRet = new Hashtable(); try { string sOldPwd = CConvert.ToString(context.Request["opwd"]).Trim(); string sNewPwd = CConvert.ToString(context.Request["npwd"]).Trim(); FastReadServer.admin.UserInfo user = (FastReadServer.admin.UserInfo)context.Session[FastReadServer.admin.CConst.CSession.C_UserInfoKey]; if (user == null || user.UserId == "") { htRet["msg"] = "用户信息超时,请重新登录!"; htRet["ok"] = false; return(htRet); } string sUid = user.UserId; DBIndex dbm = new DBIndex(); DataSet ds = new DBLogin().GetUserInfoById(sUid); if (ds.Tables[0].Rows.Count == 0) { htRet["msg"] = "用户不存在!"; htRet["ok"] = false; return(htRet); } if (System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sOldPwd, "MD5") != CConvert.ToString(ds.Tables[0].Rows[0]["pwd"])) { htRet["msg"] = "旧密码不正确!"; htRet["ok"] = false; return(htRet); } int iRet = dbm.ChangePwd(sUid, System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sNewPwd, "MD5")); if (iRet == 0) { htRet["msg"] = "服务器异常,请联系管理员!"; htRet["ok"] = false; return(htRet); } else { htRet["ok"] = true; } } catch (Exception ex) { htRet["ok"] = false; htRet["msg"] = "处理失败!" + ex.Message; } return(htRet); }
public ActionResult Logout() { if (this.Session["authorized"] != null) { DBLoginRepository loginRepository = new DBLoginRepository(this.DatabaseContext); DBLogin login = loginRepository.Find((this.Session["authorized"] as DBLogin).ID); login.UTCLogoutTime = DateTime.UtcNow; loginRepository.Update(login, true); this.Session["authorized"] = null; } return(View("Index")); }
private void btnCreate_Click(object sender, EventArgs e) { // Evita duplos cliques // btnCreate.Enabled = false; // Obtem os valores preenchidos no form server = txtServer.Text; saLogin = (DBLogin)txtSALogin.Tag; // Tenta abrir a conexão com o banco if (!OpenConnection()) { return; } // Obtem a versão do SQL Server sqlVersion = GetSQLServerVersion(); // Tenta criar o usuário do sistema no banco if (!CreateSysUser()) { return; } // Tenta criar o arquivo de configuração para acesso do sistema if (!CreateDataAccess()) { return; } // Executa os scripts a partir do container if (!RunDBScripts()) { return; } // Exibe mensagem de sucesso nas operações // btnCreate.Enabled = true; MessageBox.Show("Todas as operações foram executadas com sucesso!"); // Repassa as informações de login para o form principal DBAccess saAccess = new DBAccess(server, saLogin); if (listener != null) { listener.NotifyObject(saAccess); } // Encerra a conexão com o banco e fecha a janela CloseConnection(); this.Close(); }
public static int SaveUser(DBUser user) { int userId = user.Id; using (ApplicationContext db = new ApplicationContext()) { DBUser usr; if (userId < 1) { userId = db.Users.OrderBy(x => x.Id).LastOrDefault()?.Id ?? 1; user.Id = ++userId; db.Users.Add(user); usr = user; } else { usr = db.Users.FirstOrDefault(x => x.Id == userId); if (usr == null) { throw new Exception($"Нет записи user с таким Id = {userId}"); } user.CityId = usr.CityId; db.Entry(usr).CurrentValues.SetValues(user); //db.Update(usr); } db.SaveChanges(); usr = db.Users.FirstOrDefault(x => x.Id == userId); foreach (var login in user.Logins) { DBLogin lgn = db.Logins .FirstOrDefault(x => x.Login == login.Login); if (lgn == null) { lgn = login; lgn.UserId = userId; db.Logins.Add(lgn); } else { lgn = login; } } db.SaveChanges(); } return(userId); }
public ActionResult DeleteLogin(int id) { if (this.Authorizer.IsLogedIn(this.Session, this.Request)) { this.Authorizer.ReauthorizeLogin(this.Session); DBLoginRepository repository = new DBLoginRepository(this.DatabaseContext); DBLogin login = repository.Find(id); if ((this.Session["authorized"] as DBLogin).ID != id) { repository.Remove(login, true); } return(RedirectToAction("Logins")); } return(RedirectToAction("Index", "Login")); }
private void InitTestDb() { if (!File.Exists("Login.sqlite")) { using (var db = new DBLogin()) { db.CreateTable <Account>(); db.CreateTable <Session>(); } } if (!LoginService.ExistsAccount("testuser")) { LoginService.CreateAccount("testuser", "*****@*****.**", "TestPass"); } }
public async Task <bool> CheckPrivilege(string username, string apikey) { if (username.IsNotWhitespace() && apikey.IsNotWhitespace()) { try { DBLogin dbLogin = await DBLogin.SP_Account_Login_GetAsync(Ctx, username, apikey).ConfigureAwait(false); return(dbLogin != null && HashUtils.VerifyHashMatch256(apikey, dbLogin.UserName, dbLogin.APIKeyHash)); } catch { if (Ctx.Config.IsDebugMode) { throw; } } } return(false); }
public static void UpdateSessionKey(string username, byte[] key) { using (var db = new DBLogin()) { var acctId = db.Account.FirstOrDefault(a => a.Username == username).AccountID; db.Session.InsertOrUpdate( () => new Session { AccountID = acctId, SessionKey = key }, s => new Session { SessionKey = key }); } }
public static void CreateAccount(string username, string email, string password) { username = username.ToUpper(); password = password.ToUpper(); using (var db = new DBLogin()) using (var sha = SHA1.Create()) { var srp = new SRP(username, password); var statement = db.Account .Value(a => a.Username, username) .Value(a => a.PasswordHash, sha.ComputeHash(Encoding.ASCII.GetBytes(password))) .Value(a => a.Email, email) .Value(a => a.SRPVerifier, srp.Verifier.ToProperByteArray()) .Value(a => a.SRPSalt, srp.Salt.ToProperByteArray()); statement.Insert(); } }
protected void B_Ingresar_Click(object sender, EventArgs e) { EUsuario datosUsuario = new EUsuario(); LFuncion lFuncion = new LFuncion(); datosUsuario.Identificacion = Tx_Identificacion.Text.ToString(); datosUsuario.Password = Tx_contrasena.Text.ToString(); DBLogin traerUsuario = new DBLogin(); DataTable usuario = traerUsuario.Login(datosUsuario); if (usuario.Rows.Count == 0) { L_Informacion.Text = "Usuario o contraseña incorrectos"; Session["usuario"] = null; } else { if (int.Parse(usuario.Rows[0]["tipo"].ToString()) == 3) { Session["usuario"] = lFuncion.dataTableToEUsuario(usuario); Session["casa"] = "~/View/Usuario/AsignarCita.aspx"; Response.Redirect("~/View/Usuario/AsignarCita.aspx"); } else if (int.Parse(usuario.Rows[0]["tipo"].ToString()) == 2) { Session["usuario"] = lFuncion.dataTableToEMedico(usuario); Session["identificacion_medico"] = datosUsuario.Identificacion; Session["casa"] = "~/View/Medico/VerPacientes.aspx"; Response.Redirect("~/View/Medico/VerPacientes.aspx"); } else if (int.Parse(usuario.Rows[0]["tipo"].ToString()) == 1) { EUsuario eUsuario = new EUsuario(); eUsuario.TipoUsuario = 1; Session["usuario"] = eUsuario; Session["casa"] = "~/View/Administrador/VerUsuarios.aspx"; Response.Redirect("~/View/Administrador/VerUsuarios.aspx"); } } }
/// <summary> /// 修改记录连接 /// </summary> /// <returns></returns> private bool UpdateConnection(string ConnectStr) { if (ckbRember.Checked) { new DBLogin() { IsRead = 0 }.GDUpdate(); } string DataBaseType = SelDataType.Text; string Ip = SelIp.Text; string DataName = txtDataBaseName.Text; string UserName = txtUserName.Text; string Port = txtPort.Text; string ConnStr = ConnectionStr; int IsRead = (ckbRember.Checked ? 1 : 0); int Id = Convert.ToInt32(SelIp.SelectedValue.ToString() == "" ? "0" : SelIp.SelectedValue.ToString()); int c = new DBLogin().GDList(w => w.BaseName == DataBaseType && w.Ip == Ip && w.Port == Port && w.DataName == DataName && w.UserName == UserName).Count(); DBLogin dbModel = new DBLogin() { BaseName = DataBaseType, Ip = Ip, Port = txtPort.Text, DataName = DataName, IsRead = IsRead, PassWord = txtPassword.Text, UserName = txtUserName.Text, ConnectStr = ConnStr }; //给连接的公共属性赋值 DBInfo = dbModel; if (c > 0) { return(dbModel.GDUpdate(w => w.Id == Id)); } else { return(dbModel.GDAdd()); } }
private void Awake() { if (Singleton != null) { Destroy(gameObject); return; } Singleton = this; DontDestroyOnLoad(gameObject); GameDatabase = gameDatabase; if (GameDatabase == null) { Debug.LogError("`Game Database` has not been set"); } else { GameDatabase.Setup(); } DBManager.instance.Init(); dbTableUtils = new DBTableUtils(); dbTableUtils.Init(); dbDataUtils = new DBDataUtils(); dbDataUtils.Init(); dbLogin = new DBLogin(); dbPlayerData = new DBPlayerData(); dbBattle = new DBBattle(); dbMapItem = new DBMapItem(); dbMapItem.Init(); //GameService.onServiceStart.RemoveListener(OnGameServiceStart); //GameService.onServiceStart.AddListener(OnGameServiceStart); //GameService.onServiceFinish.RemoveListener(OnGameServiceFinish); //GameService.onServiceFinish.AddListener(OnGameServiceFinish); HideMessageDialog(); HideRewardItemsDialog(); HideLoading(); }
/// <summary> /// Returns null if login failed. /// </summary> /// <param name="db"></param> /// <param name="user"></param> /// <param name="password"></param> /// <returns></returns> public static DBLogin Login(DB db, string login, string password, string ip4, bool @readonly) { DBLogin result; int id; Logger.Log(2, "DBLogin.Login ('{0}', '{1}', '{2}'. {3})", login, password, ip4, @readonly); using (IDbCommand cmd = db.CreateCommand()) { // TODO: Encrypt passwords somehow, not store as plaintext. cmd.CommandText = "SELECT id FROM Person WHERE login = @login AND password = @password;"; DB.CreateParameter(cmd, "login", login); DB.CreateParameter(cmd, "password", password); using (IDataReader reader = cmd.ExecuteReader()) { if (!reader.Read()) { return(null); } id = reader.GetInt32(0); //if (reader.Read ()) // return null; } } result = new DBLogin(); result.person_id = id; result.ip4 = ip4; if (!@readonly) { result.expires = DateTime.Now.AddDays(1); result.cookie = CreateCookie(); result.Save(db); } return(result); }
private void btnIniciar_Click(object sender, EventArgs e) { btnIniciar.Enabled = false; String server = txtServer.Text; DBLogin saLogin = new DBLogin(txtUsername.Text, txtPassword.Text); // Cria o diretório onde para onde os dados serão exportados String baseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location.ToString()); String dataDirectory = PathFormat.Adjust(baseDir) + "Data"; Directory.CreateDirectory(dataDirectory); // Executa a exportação dos databases Recovery recovery = new Recovery(new DBAccess(server, saLogin), dataDirectory); recovery.DBExport("AppCommon"); recovery.DBExport("Accounting"); btnIniciar.Enabled = true; MessageBox.Show("Backup dos dados concluído"); }
public async Task <ApiResult> VerifyApiKey(string username, string apikey) { ApiResult apiresult = new ApiResult(); if (String.IsNullOrWhiteSpace(username)) { return(apiresult.Failure("Invalid Username.")); } if (apikey?.Length != HashUtils.APIKeyLength256) { return(apiresult.Failure("Invalid APIKey.")); } if (this.UserContext == null) { return(apiresult.Failure("You do not have permission to perform this action.")); } if (!this.UserContext.IsVerifiedLogin) { return(apiresult.Failure("Login Credentials Expired. Try Relogging In.")); } DBLogin dbLogin; try { dbLogin = await DBLogin.SP_Account_Login_GetAsync(WebAppContext.Factory, username, apikey).ConfigureAwait(false); } catch (Exception ex) { return(apiresult.Failure(ex)); } if (dbLogin != null && HashUtils.VerifyHashMatch256(apikey, dbLogin.UserName, dbLogin.APIKeyHash)) { apiresult.Success("Is Valid ApiKey"); } else { apiresult.Failure("ApiKey is Invalid"); } return(apiresult); }
private void btnCreate_Click(object sender, EventArgs e) { if (String.IsNullOrEmpty(txtUsername.Text)) { ShowWarning("É necessário definir o username!"); return; } if (String.IsNullOrEmpty(txtPassword.Text)) { ShowWarning("É necessário definir o password!"); return; } DBLogin newDBLogin = new DBLogin(txtUsername.Text, txtPassword.Text); if (listener != null) { listener.NotifyObject(newDBLogin); } this.Close(); }
public static bool HandleAuthSession(GatewayConnection client, BinaryReader br) { var pkt = PacketHelper.Parse <CMSG_AUTH_SESSION>(br); // TODO: verify build client.Crypt = new AuthCrypt(LoginService.GetSessionKey(pkt.Account)); var serverDigest = HashUtil.ComputeHash(Encoding.ASCII.GetBytes(pkt.Account), new byte[] { 0, 0, 0, 0 }, BitConverter.GetBytes(pkt.ClientSeed), BitConverter.GetBytes(client.Seed), client.Crypt.SessionKey); if (!serverDigest.SequenceEqual(pkt.ClientDigest)) { return(false); } // TODO: Move to LoginService? using (var db = new DBLogin()) { var acc = db.Account.FirstOrDefault(a => a.Username == pkt.Account); client.AccountName = acc.Username; client.AccountID = acc.AccountID; } client.SendPacket(WorldOpcodes.SMSG_AUTH_RESPONSE, PacketHelper.Build(new SMSG_AUTH_RESPONSE { Response = (byte)ResponseCodes.AUTH_OK, BillingTimeRemaining = 0, BillingPlanFlags = 0, BillingTimeRested = 0 })); return(true); }
public LoginCtrl() { dbLogin = new DBLogin(); }