/// <summary> /// プレイヤーをログインさせる。 /// </summary> /// <returns>処理状態。</returns> private async Task Login() { PlayerEntity player; AuthEntity auth = this.localRepository.LoadAuth(); if (auth != null) { // 認証情報がある場合は、それで認証する // TODO: 認証失敗時の処理を考える player = await this.playerRepository.Login(auth.Id, auth.Token); } else { // 認証情報が無い場合は、新規作成する var token = AuthEntity.NewToken(); player = await this.playerRepository.CreatePlayer(token); auth = new AuthEntity() { Id = player.Id, Token = token }; this.localRepository.SaveAuth(auth); } this.global.AuthEntity = auth; this.global.PlayerEntity = player; }
public Form1(bool isSilent) { this.isSilent = isSilent; InitializeComponent(); try { System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); string version = fvi.FileVersion; this.Text += " [" + version + "]"; string jsonString = FileHelper.Instance.GetStringFromFilePath("agroapi.io.json"); ScicropEntity scicropEntity = ScicropEntity.FromJson(jsonString); authEntity = scicropEntity.AuthEntity; label2.Text = authEntity.UserEntity.Email; GetLastRun(); if (isSilent) { Run(); } } catch (Exception e) { updateStatus("Error: " + e.Message); } }
private async Task <bool> authenticationLogin() { //string post = "{\"username\" : \""+lbl_empID.Text +"\" \"password\": \""+lbl_pwd.Text+"\"}"; AuthEntity post = new AuthEntity(); post.username = Convert.ToDecimal(lbl_empID.Text); post.password = lbl_pwd.Text; bool success = await WebServices.Webservice.Instance.Authenticate(post); if (success) { await Navigation.PushPopupAsync(new InitialPleaseWait("Success!!")); await DatabaseManager.InitialSync(Navigation); /*if (Device.RuntimePlatform == Device.iOS) * { * await Navigation.PushModalAsync(new MainPage()); * } * * else * { * await Navigation.PushAsync(new MainPage()); * }*/ } else { // MessagingCenter.Send<LoginPage>(this, "LoginPopUpRemoval"); await Navigation.PopPopupAsync(); await DisplayAlert("Login Failed", "Username or password incorrect.", "OK"); } return(success); }
protected void RegisterUser(object sender, EventArgs e) { try { using (var db = new OrganizerEntities()) { var userNameAndEmail = txtEmail.Text; var password = txtPassword.Text; var passwordConfirmation = txtConfirmPassword.Text; if (password != passwordConfirmation) { result.Text = "Passwords don't match"; result.ForeColor = Color.Red; return; } if (db.AuthEntities.Any(x => x.UserName == userNameAndEmail)) { result.Text = String.Format("User '{0}' already exists in database", userNameAndEmail); result.ForeColor = Color.Red; return; } var newUser = new AuthEntity { Id = Guid.NewGuid(), Password = password, UserName = userNameAndEmail, RegisteredAtUtc = DateTime.UtcNow, LastActiveAtUtc = DateTime.UtcNow, RegisteredFromIpAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] }; db.AuthEntities.Add(newUser); db.SaveChanges(); db.TreeItems.Add(new TreeItem { AuthEntityId = newUser.Id, Id = Guid.NewGuid(), CreatedUtc = DateTime.UtcNow, IsCollapsed = false, LastModifiedUtc = DateTime.UtcNow, ParentId = null, NextSiblingId = null, Text = "root item (click here to rename and to add child items)" }); db.SaveChanges(); result.Text = "Thank you for registration"; result.ForeColor = Color.Green; } } catch (Exception exc) { Global.HandleException(exc); result.Text = "An error occured. Please contact technical support"; result.ForeColor = Color.Red; return; } Response.Redirect("Login.aspx"); }
public static UserEntity Create(AddUserModel addUserModel, AuthEntity authEntity) { return(new UserEntity ( new FullName(addUserModel.FullName.Name, addUserModel.FullName.Surname), new Email(addUserModel.Email), authEntity )); }
public void Create(AuthEntity authEntity) { if (!CheckForExistingEmail(authEntity)) { _unitOfWork.Profiles.Create(new Profile() { Password = authEntity. Password, Email = authEntity.Email }); _unitOfWork.Commit(); } }
private TokenModel CreateToken(AuthEntity authEntity) { var claims = new List <Claim>(); claims.AddSub(authEntity.Id.ToString()); claims.AddRoles(authEntity.Roles.ToArray()); var token = _jsonWebTokenService.Encode(claims); return(new TokenModel(token)); }
public IActionResult RefreshProfile(int uid) { try { AuthEntity res = _authService.Refresh(uid); return(Ok(res)); } catch { return(BadRequest()); } }
public async Task<bool> RequestCodeAsync(string phoneNumber) { var test = PhoneNumberUtil.GetInstance(); var parsedNumber = test.Parse(phoneNumber, "US"); var newNumber = test.Format(parsedNumber, PhoneNumberFormat.E164); var phone = new AuthEntity() { phone = newNumber }; var result = await _webManager.PostData(new Uri(Endpoints.RequestCode), null, new StringContent(JsonConvert.SerializeObject(phone), Encoding.UTF8, "application/json")); var response = JsonConvert.DeserializeObject<AuthResponse>(result.ResultJson); return response.Success == 1; }
public async Task<AuthResponse> RegisterAsync(string phoneNumber, string code, string timezone = "America/New_York") { var test = PhoneNumberUtil.GetInstance(); var parsedNumber = test.Parse(phoneNumber, "US"); var newNumber = test.Format(parsedNumber, PhoneNumberFormat.E164); var phone = new AuthEntity() { code = code, phone = newNumber, timezone = timezone }; var result = await _webManager.PostData(new Uri(Endpoints.Auth), null, new StringContent(JsonConvert.SerializeObject(phone), Encoding.UTF8, "application/json")); return JsonConvert.DeserializeObject<AuthResponse>(result.ResultJson); }
public bool IncrementTours(AuthEntity user) { var dbEntry = _auc.Users.FirstOrDefault(acc => acc.UserId == user.UserId); if (dbEntry != null) { dbEntry.ToursCompleted += 1; _auc.SaveChanges(); return(true); } else { return(false); } }
public async Task <bool> RequestCodeAsync(string phoneNumber) { var test = PhoneNumberUtil.GetInstance(); var parsedNumber = test.Parse(phoneNumber, "US"); var newNumber = test.Format(parsedNumber, PhoneNumberFormat.E164); var phone = new AuthEntity() { phone = newNumber }; var result = await _webManager.PostData(new Uri(Endpoints.RequestCode), null, new StringContent(JsonConvert.SerializeObject(phone), Encoding.UTF8, "application/json")); var response = JsonConvert.DeserializeObject <AuthResponse>(result.ResultJson); return(response.Success == 1); }
public async Task <AuthResponse> RegisterAsync(string phoneNumber, string code, string timezone = "America/New_York") { var test = PhoneNumberUtil.GetInstance(); var parsedNumber = test.Parse(phoneNumber, "US"); var newNumber = test.Format(parsedNumber, PhoneNumberFormat.E164); var phone = new AuthEntity() { code = code, phone = newNumber, timezone = timezone }; var result = await _webManager.PostData(new Uri(Endpoints.Auth), null, new StringContent(JsonConvert.SerializeObject(phone), Encoding.UTF8, "application/json")); return(JsonConvert.DeserializeObject <AuthResponse>(result.ResultJson)); }
/// <summary> /// throws exception if access is denied /// </summary> /// <param name="treeItem">tree item which is being accessed</param> /// <param name="db"></param> /// <param name="write">which kind of access we need: read or write (read for readonly links) (write=false)</param> /// <returns>AuthEntity (user account record) to set LastActiveAtUtc field (to avoid deletion of account and its tree items on idle timer expiry)</returns> public static AuthEntity ValidateAccessToTreeItem_ReturnActiveAuthEntity(TreeItem treeItem, OrganizerEntities db, bool write) { AuthEntity currentAuthenticatedAuthEntity = null; if (HttpContext.Current.Request.IsAuthenticated) { currentAuthenticatedAuthEntity = db.AuthEntities.First(x => x.UserName == HttpContext.Current.User.Identity.Name); } // go to first parent item with not-null authEntityId var rootItem = GetRootTreeItemToValidateAccess(treeItem, db, currentAuthenticatedAuthEntity); if (currentAuthenticatedAuthEntity == null) { if (write) { if (rootItem.ShareWrite == null || rootItem.ShareWrite == false) { throw new UnauthorizedAccessException("drf sdf sgdfg"); } } else { if (rootItem.ShareRead == null || rootItem.ShareRead == false) { throw new UnauthorizedAccessException("23451234x52345"); } } return(GetRootTreeItem(rootItem, db).AuthEntity); } else { // if we access root item with ShareRead == true then we don't need to do any authentication if (treeItem.ShareRead == true && write == false) { // here we have 2 accounts to mark as active: currentAuthenticatedAuthEntity (currently logged in user) // or GetRootTreeItem(rootItem, db).AuthEntity (user who shared the link) return(GetRootTreeItem(rootItem, db).AuthEntity); } if (rootItem.AuthEntityId != currentAuthenticatedAuthEntity.Id) { throw new UnauthorizedAccessException("sdfs dgsdfg234234 rootItem.ShareRead = " + rootItem.ShareRead + " write=" + write); } return(currentAuthenticatedAuthEntity); } }
public IActionResult Register([FromBody] AuthEntity user) { try { bool res = _authService.Register(user); if (res == false) { return(BadRequest("Email already in use")); } return(Ok()); } catch { return(BadRequest()); } }
private IResult Validate(AuthEntity authEntity, SignInModel signInModel) { if (authEntity == default || signInModel == default) { return(Result.Fail(Texts.SignInError)); } var password = _hashService.Create(signInModel.Password, authEntity.Salt); if (authEntity.Password != password) { return(Result.Fail(Texts.SignInError)); } return(Result.Success()); }
/// <summary> /// 得到一个对象实体 /// </summary> /// <param name="row">row.</param> /// 创建者:解志辉 private AuthEntity DataRowToModel(DataRow row) { var model = new AuthEntity(); if (row != null) { if (row["AppId"] != null && row["AppId"].ToString() != "") { model.appId = int.Parse(row["AppId"].ToString()); } if (row["AppName"] != null) { model.appName = row["AppName"].ToString(); } if (row["AppSecret"] != null) { model.appSecret = row["AppSecret"].ToString(); } if (row["AppSafeCode"] != null) { model.appSafeCode = row["AppSafeCode"].ToString(); } if (row["AppServerIps"] != null) { model.appServerIps = row["AppServerIps"].ToString(); } if (row["IsDelete"] != null && row["IsDelete"].ToString() != "") { model.isDelete = int.Parse(row["IsDelete"].ToString()); } if (row["AppStatus"] != null && row["AppStatus"].ToString() != "") { model.appStatus = int.Parse(row["AppStatus"].ToString()); } if (row["CreatedOn"] != null && row["CreatedOn"].ToString() != "") { model.createdOn = DateTime.Parse(row["CreatedOn"].ToString()); } if (row["UpdatedOn"] != null && row["UpdatedOn"].ToString() != "") { model.updatedOn = DateTime.Parse(row["UpdatedOn"].ToString()); } } return(model); }
public IActionResult IncrementPlaces([FromBody] AuthEntity user) { try { bool res = _authService.IncrementPlaces(user); if (res == false) { return(NotFound()); } else { return(Ok()); } } catch { return(BadRequest()); } }
public async Task <IActionResult> GetToken([FromBody] AuthEntity data) { var result = new ResponseBase <string>(); var userAuth = new ResponseBase <bool>(); //Escriba aquí la implementación para validar usuario y contraseña de acceso userAuth = await new ExampleDao().SimulateLogin(data.UserName, data.Password); if (userAuth.Code == 200 && userAuth.Data) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, data.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var token = new JwtSecurityToken ( issuer: config["token:issuer"], audience: config["token:audience"], claims: claims, expires: DateTime.UtcNow.AddHours(double.Parse(config["token:expire"])), notBefore: DateTime.UtcNow, signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["token:signingkey"])), SecurityAlgorithms.HmacSha256) ); result.Code = (int)HttpStatusCode.OK; result.Data = new JwtSecurityTokenHandler().WriteToken(token); result.Message = userAuth.Message; return(Ok(result)); } else { result.Code = (int)HttpStatusCode.Unauthorized; result.Message = userAuth.Message; result.Data = ""; return(StatusCode(result.Code, result)); } }
public bool RegisterAccount(AuthEntity user) { var dbEntry = _auc.Users.FirstOrDefault(acc => acc.Email == user.Email); if (dbEntry != null) { return(false); } using (HashAlgorithm alg = SHA256.Create()) { string password = Encoding.UTF8.GetString(alg.ComputeHash(Encoding.UTF8.GetBytes(user.Passw))); user.Passw = password; } user.Image = "https://moonvillageassociation.org/wp-content/uploads/2018/06/default-profile-picture1.jpg"; user.PlacesVisited = 0; user.ToursCompleted = 0; _auc.Users.Add(user); _auc.SaveChanges(); return(true); }
static void Main(string[] args) { try { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start();//开始计时 DataTable dtz = MySQLHelper.Query("SELECT * from zones where id=3118661").Tables[0]; DataTable dta = MySQLHelper.Query("SELECT * from authorities where zoneid=3118661").Tables[0]; DataTable dtd = MySQLHelper.Query("SELECT * from dnsrecords where zoneid=3118661").Tables[0]; List <Zones> zonesList = DtToList <Zones> .ConvertToModel(dtz); Zones zone = zonesList[0]; ZonesEntity ze = new ZonesEntity(); ze.id = Utility.StringHelper.CalculateMD5Hash(zone.Zone + ".").ToLower(); ze.userid = Convert.ToInt32(zone.UserID); ze.domain = zone.Zone; ze.level = zone.DomainLevel > 0 ? 1 : 0; ze.nsstate = zone.NSState; ze.is_stop = zone.Active == "Y" ? "N" : "Y"; ze.force_stop = zone.ForceStop; ze.rdomain = zone.RZone; List <AuthEntity> alist = new List <AuthEntity>(); foreach (DataRow dr in dta.Rows) { AuthEntity ae = new AuthEntity(); ae.rid = Convert.ToInt32(dr["id"]); ae.domain = ze.domain; ae.name = dr["host"].ToString(); ae.type = dr["type"].ToString(); if (ae.type == "SOA") { //Mbox,Serial,Refresh,Retry,Expire,Minimum ae.rdata = dr["data"].ToString() + " " + dr["mbox"].ToString() + " " + dr["serial"].ToString() + " " + dr["refresh"].ToString() + " " + dr["retry"].ToString() + " " + dr["expire"].ToString() + " " + dr["minimum"].ToString(); } else { ae.rdata = dr["data"].ToString(); } ae.ttl = Convert.ToInt32(dr["ttl"]); ae.view = "Def"; ae.view = "Y"; alist.Add(ae); } List <RecordEntity> rlist = new List <RecordEntity>(); foreach (DataRow dr in dtd.Rows) { RecordEntity re = new RecordEntity(); re.rid = Convert.ToInt32(dr["id"]); re.domain = ze.domain; re.name = dr["host"].ToString(); re.type = dr["type"].ToString(); if (re.type == "MX") { //Mbox,Serial,Refresh,Retry,Expire,Minimum re.rdata = dr["mx_priority"].ToString() + " " + dr["data"].ToString(); } else if (re.type == "TXT") { re.rdata = dr["data"].ToString().Replace("\"", string.Empty); } else { re.rdata = dr["data"].ToString(); } re.ttl = Convert.ToInt32(dr["ttl"]); re.view = dr["view"].ToString(); re.view = dr["active"].ToString() == "Y" ? "N" : "Y"; rlist.Add(re); } ze.authorities = alist; ze.records = rlist; var client = DriverConfiguration.Client; var db = client.GetDatabase(DriverConfiguration.DatabaseNamespace.DatabaseName); IMongoCollection <ZonesEntity> categories = db.GetCollection <ZonesEntity>("ZonesEntiy"); categories.InsertOne(ze); Console.WriteLine("MongoDB Inserted; Use time={0};", watch.ElapsedMilliseconds); watch.Stop();//停止计时 } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public bool IncrementPlaces(AuthEntity user) { return(_increment.IncrementPlaces(user)); }
public bool Register(AuthEntity user) { return(_register.RegisterAccount(user)); }
private bool CheckForExistingEmail(AuthEntity authEntity) { return(_unitOfWork.Profiles.GetOneByPredicate(p => p.Email == authEntity.Email) != null); }
static TreeItem GetRootTreeItemToValidateAccess(TreeItem treeItem, OrganizerEntities db, AuthEntity currentAuthenticatedAuthEntity) { if (treeItem.AuthEntityId != null) { return(treeItem); } if (currentAuthenticatedAuthEntity == null) { if (treeItem.ShareRead == true || treeItem.ShareWrite == true) { return(treeItem); } } if (treeItem.ParentId == null) { throw new UnauthorizedAccessException(); } var parentItem = db.TreeItems.Find(treeItem.ParentId.Value); return(GetRootTreeItemToValidateAccess(parentItem, db, currentAuthenticatedAuthEntity)); }
protected void Page_Load(object sender, EventArgs e) { Global.RequireHttps(); var rootTreeItemStr = Request["RootTreeItemId"]; using (var db = new OrganizerEntities()) { AuthEntity currentlyLoggedInUser = null; if (Request.IsAuthenticated) { currentlyLoggedInUser = db.AuthEntities.First(x => x.UserName == HttpContext.Current.User.Identity.Name); } TreeItem rootTreeItem = null; bool writeAccess = false, readAccess = false; if (String.IsNullOrEmpty(rootTreeItemStr)) { if (currentlyLoggedInUser == null) { Response.Redirect("/Login.aspx?url=" + HttpUtility.UrlEncode(Request.Url.ToString())); return; } rootTreeItem = db.TreeItems.First(x => x.AuthEntityId == currentlyLoggedInUser.Id && x.ParentId == null); CustomMembershipProvider.ValidateAccessToTreeItem_ReturnActiveAuthEntity(rootTreeItem, db, true); writeAccess = true; } else { var rootTreeItemId = Guid.Parse(rootTreeItemStr); rootTreeItem = db.TreeItems.Find(rootTreeItemId); if (currentlyLoggedInUser != null) { // if currently logged in user is not equal to root tree item's user then we try to get readonly access if (currentlyLoggedInUser.Id != GetTopRootItem(db, rootTreeItem).AuthEntityId&& rootTreeItem.ShareRead == true) { CustomMembershipProvider.ValidateAccessToTreeItem_ReturnActiveAuthEntity(rootTreeItem, db, false); readAccess = true; } else { CustomMembershipProvider.ValidateAccessToTreeItem_ReturnActiveAuthEntity(rootTreeItem, db, true); writeAccess = true; } } else { if (rootTreeItem.ShareWrite == true) { writeAccess = true; } if (rootTreeItem.ShareRead == true) { readAccess = true; } } } titleElement.InnerText = rootTreeItem.Text; if (writeAccess) { organizer.RootTreeItemId = rootTreeItem.Id.ToString(); } else if (readAccess) { readonlyDisplay.InnerHtml = GetTreeItems.RenderTreeItemsReadonly(db, rootTreeItem); } else { Response.Redirect("/Login.aspx?url=" + HttpUtility.UrlEncode(Request.Url.ToString())); } } }
/// <summary> /// 認証情報を保存する。 /// </summary> /// <param name="auth">認証情報。</param> public void SaveAuth(AuthEntity auth) { PlayerPrefs.SetInt("PlayerId", auth.Id); PlayerPrefs.SetString("PlayerToken", auth.Token); PlayerPrefs.Save(); }
public void Edit(AuthEntity prop) { throw new NotImplementedException(); }