public async Task <dynamic> Register(RegistrationRequest model) { HttpResponseMessage responce = Utils.CheckModel(model, Request); if (!responce.IsSuccessStatusCode) { return(responce); } var user = new ApplicationUser() { PhoneNumber = model.phone, FirstName = model.firstName, LastName = model.lastName, OTPSecret = Base.LoginUtils.generateSalt() }; //create user user.UserName = Guid.NewGuid().ToString(); //give the USername a value, for soem reason IdentityResult result = new IdentityResult(); try { // Your code... // Could also be before try if you know the exception occurs in SaveChanges result = await UserManager.CreateAsync(user, model.Password); } catch (Exception original) { Exception innermost = original; while (innermost.InnerException != null) { innermost = innermost.InnerException; } if (innermost.GetType() == typeof(System.Data.SqlClient.SqlException)) // true) { var sqlException = (System.Data.SqlClient.SqlException)innermost; if (sqlException.Number == 2601) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.PhoneTaken)); } } return(innermost); } if (result.Succeeded) { string otp = Base.LoginUtils.GenerateOTP(user); await SMSService.SendMessage(model.phone.ToString(), "Welcome to Hive, your code is " + otp + " use it to confirm your phone number within 5 min"); return(responce); } else { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.SomethingHappened)); } }
/// <summary> /// Will delete a ralationship between you and another user, as long as you are not the one that was blocked /// </summary> /// <param name="id">ID of the RELATIONSHIP not the user</param> /// <returns>Returns OK if done, and ErrorResponce if there is an error</returns> public async Task <dynamic> Delete([FromUri] long id) { var UserId = long.Parse(User.Identity.GetUserId()); var contactDb = await db.Contacts.FirstOrDefaultAsync( p => (p.Person1Id == UserId && p.Id == id) || (p.Id == id && p.Person2Id == UserId)); if (contactDb == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.DoesntExist)); } var contact = contactDb.ToContact(UserId); if (contact.state == ContactDb.StateBlockedP1) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.IllegalChanges)); } db.Contacts.Remove(contactDb); await db.SaveChangesAsync(); var parties = await db.Users.Where(p => p.Id == contactDb.Person1Id || p.Id == contactDb.Person2Id).ToArrayAsync(); long phone = parties.First(p => p.Id != UserId).PhoneNumber; string actorName = parties.First(p => p.Id == UserId).FirstName + " " + parties.First(p => p.Id == UserId).LastName; string SmsMesage = "Hive: " + actorName + " has deleted you!"; SMSService.SendMessage(phone.ToString(), SmsMesage); //We don;t want to await an SMS, really return(Ok()); }
/// <summary> /// By submitting ID of the user in the body of the request, you can attempt to "Friend" them /// </summary> /// <param name="contactID">returns 200 if successfull, or will reply if unsuccessfull</param> public async Task <dynamic> Post([FromBody] long contactID) { var UserId = long.Parse(User.Identity.GetUserId()); bool exists = await db.Contacts.AnyAsync( p => (p.Person1Id == UserId && p.Person2Id == contactID) || (p.Person1Id == contactID && p.Person2Id == UserId)); if (exists) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.CantOverrite)); } if (!await db.Users.AnyAsync(u => u.Id == contactID)) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.DoesntExist)); } ContactDb newContact = new ContactDb { State = ContactDb.StatePendingP2, Person1Id = UserId, Person2Id = contactID }; db.Contacts.Add(newContact); await db.SaveChangesAsync(); var parties = await db.Users.Where(p => p.Id == contactID || p.Id == UserId).ToArrayAsync(); long phone = parties.First(p => p.Id == contactID).PhoneNumber; string actorName = parties.First(p => p.Id == UserId).FirstName + " " + parties.First(p => p.Id == UserId).LastName; string message = "Hive: " + String.Format("{0} has sent you a friend request!", actorName); SMSService.SendMessage(phone.ToString(), message); //We don;t want to await an SMS, really return(Ok(newContact.ToContact(UserId))); }
public async Task <dynamic> RequestSMSCode(SMSRequest model) { HttpResponseMessage responce = Utils.CheckModel(model, Request); if (!responce.IsSuccessStatusCode) { return(responce); } ApplicationUser user = await LoginUtils.findByIdentifierAsync(model.phone.ToString(), UserManager); if (user == null || !String.Equals(user.LastName, model.lastName, StringComparison.OrdinalIgnoreCase)) //if the user does not exist, or if their last name does not match phone number { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.CantLogin)); } else { string otp = Base.LoginUtils.GenerateOTP(user); await SMSService.SendMessage(model.phone.ToString(), String.Format("Your SMS code is {0} use it to login within {1} min", otp, LoginUtils.Interval / 60)); } return(responce); }
/// <summary> /// Adds staff to the ORganisation /// </summary> /// <param name="newStaff">Staff to be added. Essentially you choose the OrgID of the Organisation to add staff to, the ID of the person to add, and his role</param> /// <returns></returns> public async Task <dynamic> Post([FromBody] Staff newStaff) { if (newStaff != null) { newStaff.oldObject = false; } var UserId = long.Parse(User.Identity.GetUserId()); HttpResponseMessage responce = Utils.CheckModel(newStaff, Request); if (!responce.IsSuccessStatusCode) { return(responce); } var contacts = await db.Contacts.FirstOrDefaultAsync(b => (b.Person1Id == UserId && b.Person2Id == newStaff.personID) || (b.Person1Id == newStaff.personID && b.Person2Id == UserId)); if (contacts == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.DoesntExist)); } if (contacts.State != ContactDb.StateFriend) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.PersonNotAvaliable)); } var bindingsList = await db.Bindings.Where(b => b.OrganisationID == newStaff.onOrganisationID).Include(b => b.Organisation).ToArrayAsync(); if (bindingsList.Count() == 0) //does the spesified organisation exist { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.DoesntExist)); } var usersRole = bindingsList.FirstOrDefault(b => b.PersonID == UserId)?.Role; if (usersRole != BondDb.RoleManager && usersRole != BondDb.RoleOwner) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.CantEdit)); } //is the person already assigned as staff for this Orgonisation? if (bindingsList.Any(b => b.PersonID == newStaff.personID)) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.CantOverrite)); } if (usersRole == BondDb.RoleManager && newStaff.role == BondDb.RoleOwner) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.PermissionsTooLow)); } BondDb staffDB = new BondDb { OrganisationID = newStaff.onOrganisationID, PersonID = newStaff.personID, Role = newStaff.role }; db.Bindings.Add(staffDB); await db.SaveChangesAsync(); //Create an SMS notification var inviter = await db.Users.FirstOrDefaultAsync(i => i.Id == UserId); string inviterName = inviter.FirstName + " " + inviter.LastName; var invitee = await db.Users.FirstOrDefaultAsync(i => i.Id == staffDB.PersonID); var organisation = await db.Organisations.FirstOrDefaultAsync(f => f.Id == newStaff.onOrganisationID); string organisationName = organisation.Name; string message = String.Format("Hive: You have been assigned as {0} on {1} by {2}. Congratulations! If {2} gives you unwanted assignment, you may remove {2} from your contacts ", staffDB.Role, organisationName, inviterName); await SMSService.SendMessage(invitee.PhoneNumber.ToString(), message); return(Ok((Staff)staffDB)); }
/// <summary> Creates a job. You can assign a job to yourself, or to staff at this organisation if you role is manager or owner </summary> /// <param name="newJob">Job to be added</param> /// <returns>200 if successfull, and ErrorResponce Otherwise</returns> public async Task <dynamic> Post([FromBody] DTO.TaskDTO newJob) { if (newJob != null) { newJob.oldObject = false; } long UserId = long.Parse(User.Identity.GetUserId()); HttpResponseMessage responce = Utils.CheckModel(newJob, Request); if (!responce.IsSuccessStatusCode) { return(responce); } var theField = await db.Fields.Where(f => f.Id == newJob.forFieldID).Include(f => f.OnOrganisation).Include(f => f.OnOrganisation.Bonds).FirstOrDefaultAsync(); if (theField == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.DoesntExist)); } if (!theField.OnOrganisation.Bonds.Any(p => p.PersonID == newJob.assignedToID)) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.PersonNotAvaliable)); } string role = OrganisationsController.FindAndGetRole(theField.OnOrganisation, UserId); bool editRights = BondDb.CanAssignJobsToOthers.Contains(role); bool requestAuthorised = false; //Check user's access if (role == BondDb.RoleNone) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.CantView)); } //Self-create if (newJob.assignedToID == UserId || editRights) { requestAuthorised = true; } TaskDb job = new TaskDb { Name = newJob.name, TaskDescription = newJob.taskDescription, PayRate = newJob.payRate, State = newJob.state, Type = newJob.type, DueDate = newJob.dueDate, EventLog = string.Empty, AssignedByID = UserId, AssignedToID = newJob.assignedToID, ForFieldID = theField.Id, TimeTaken = 0, CreatedOn = DateTime.UtcNow, UpdatedOn = DateTime.UtcNow, MarkedDeleted = false }; eventLog.Add(new TaskEvent((DTO.TaskDTO)job, UserId, "Job crated")); job.EventLog = JsonConvert.SerializeObject(eventLog); if (requestAuthorised) { db.Tasks.Add(job); await db.SaveChangesAsync(); //If it makes sence, send a mesage if (newJob.assignedToID != UserId && newJob.state != TaskDb.StateFinished) { var parties = await db.Users.Where(p => p.Id == newJob.assignedToID || p.Id == UserId).ToArrayAsync(); long phone = parties.First(p => p.Id == newJob.assignedToID).PhoneNumber; string actorName = parties.First(p => p.Id == UserId).FirstName + " " + parties.First(p => p.Id == UserId).LastName; string message = "Hive: " + String.Format("{0} has assigned you a {1} task at the {2} field. For more details, see Tasks in the Hive app on your phone", actorName, newJob.type, theField.Name); SMSService.SendMessage(phone.ToString(), message); //We don;t want to await an SMS, really } return(Ok((DTO.TaskDTO)job)); } else { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.IllegalChanges)); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { /*Gets Extra keys sent form the user's computer, however we will make this unnessesary * var data = await context.Request.ReadFormAsync(); * string email = data.GetValues("email").First(); */ //setup nessesary variables var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); ApplicationUser user = null; bool loggedIn = false; if (string.IsNullOrWhiteSpace(context.Password)) //check if valid password was provided { context.SetError(ErrorResponse.PasswordIsBad.error.ToString(), ErrorResponse.PasswordIsBad.error_description); //rejects, password is wrong return; } else { user = await LoginUtils.findByIdentifierAsync(context.UserName, userManager); } if (user == null) { context.SetError(ErrorResponse.CantLogin.error.ToString(), ErrorResponse.CantLogin.error_description); //rejects, no user found return; } var PasswordCheck = userManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash, context.Password); //check if password was correct if (PasswordCheck.Equals(PasswordVerificationResult.Success) && user.PhoneNumberConfirmed) //user provided correct creentials { loggedIn = true; } else if (PasswordCheck.Equals(PasswordVerificationResult.Success)) { //Send an SMS!! string otp = Base.LoginUtils.GenerateOTP(user); await SMSService.SendMessage(user.PhoneNumber.ToString(), String.Format("Your SMS code is {0} use it to confirm your phone number withing {1} min", otp, LoginUtils.Interval / 60)); context.SetError(ErrorResponse.PhoneNumberUnconfirmed.error.ToString(), ErrorResponse.PhoneNumberUnconfirmed.error_description); } else if (!loggedIn)// log in with SMS code { loggedIn = LoginUtils.ValidateOTP(user, context.Password); if (!user.PhoneNumberConfirmed && loggedIn) //if the user's phone number is not confirmed, and if logged in set it confirmed { user.PhoneNumberConfirmed = true; await userManager.UpdateAsync(user); } } if (loggedIn) //user provided correct creentials { ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, //generates identity OAuthDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.Id.ToString()); //generates properties AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); //puts properties and idenity into authentication ticket context.Validated(ticket); } else { context.SetError(ErrorResponse.CantLogin.error.ToString(), ErrorResponse.CantLogin.error_description); //rejects, password is wrong } /*ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, * CookieAuthenticationDefaults.AuthenticationType); */ //context.Request.Context.Authentication.SignIn(cookiesIdentity); }
/// <summary> /// Will alter the person's Contacts as requested. At the moment the only thing you can alter is State, all other changed will be disregarded. /// That means you cannot rename the other person, or do anything else silly /// </summary> /// <param name="id">Id of the connection, NOT of the user</param> /// <param name="contactWeb"> The contact POCO</param> /// <returns></returns> public async Task <dynamic> Put([FromUri] long id, [FromBody] Contact contactWeb) { var UserId = long.Parse(User.Identity.GetUserId()); string message = string.Empty; HttpResponseMessage responce = Utils.CheckModel(contactWeb, Request); if (!responce.IsSuccessStatusCode) { return(responce); } var contactDb = await db.Contacts.FirstOrDefaultAsync( p => (p.Person1Id == UserId && p.Id == id) || (p.Id == id && p.Person2Id == UserId)); if (contactDb == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.DoesntExist)); } var contact = contactDb.ToContact(UserId); //when you can become friends if (contact.state == ContactDb.StatePendingP1 && contactWeb.state == ContactDb.StateFriend) { contactDb.State = ContactDb.StateFriend; message = "has accepted your friend request!"; contactDb.UpdatedOn = DateTime.UtcNow; } //when you can block the person else if (contact.state == ContactDb.StateFriend && contactWeb.state == ContactDb.StateBlockedP2 || contact.state == ContactDb.StatePendingP1 && contactWeb.state == ContactDb.StateBlockedP2) { if (contactDb.Person1Id == UserId) { contactDb.State = ContactDb.StateBlockedP2; } else { contactDb.State = ContactDb.StateBlockedP1; } message = "has blocked you!"; contactDb.UpdatedOn = DateTime.UtcNow; } else { return(Request.CreateResponse(HttpStatusCode.BadRequest, ErrorResponse.IllegalChanges)); } await db.SaveChangesAsync(); var parties = await db.Users.Where(p => p.Id == contactDb.Person1Id || p.Id == contactDb.Person2Id).ToArrayAsync(); long phone = parties.First(p => p.Id != UserId).PhoneNumber; string actorName = parties.First(p => p.Id == UserId).FirstName + " " + parties.First(p => p.Id == UserId).LastName; string SmsMesage = "Hive: " + actorName + " " + message; SMSService.SendMessage(phone.ToString(), SmsMesage); //We don;t want to await an SMS, really return(Ok(contactDb.ToContact(UserId))); }