public IHttpActionResult GetGimmickStats(int gimmickId) { if (gimmickId <= 0) { return(BadRequest("Gimmick ID is not valid!")); } try { using (var ctx = new BugghyDbContext()) { Gimmick gi = ctx.Gimmicks.SingleOrDefault(x => x.GimmickId == gimmickId); if (gi == null) { return(InternalServerError(new InvalidOperationException("Invalid Gimmick ID!"))); } var query = ctx.Issues.Where(x => x.GimmickId == gimmickId); return(Ok(Dto.Wrap(new Poco.Stats { Opened = query.Count(x => x.Status == IssueStatus.Opened), Working = query.Count(x => x.Status == IssueStatus.Evaluating || x.Status == IssueStatus.Working), Closed = query.Count(x => x.Status == IssueStatus.Resolved || x.Status == IssueStatus.Rejected || x.Status == IssueStatus.Closed) }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult GetGimmicks() { try { using (var ctx = new BugghyDbContext()) { return(Ok(Dto.Wrap(new Poco.DataBundle <Poco.Gimmick> { Items = ctx.Gimmicks .Select(x => new Poco.Gimmick { GimmickId = x.GimmickId, Name = x.Name, Description = x.Description, Owner = x.Owner, ImageUrl = x.ImageUrl, CreationDate = x.CreationDate }) .ToArray() }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public async Task <IHttpActionResult> RegisterUser(Poco.User credentials) { if (string.IsNullOrWhiteSpace(credentials.Email)) { return(BadRequest("The email is not valid!")); } if (string.IsNullOrWhiteSpace(credentials.Password)) { return(BadRequest("The password is not valid!")); } try { using (var ctx = new ChattyDbContext()) { User user = ctx.Users.SingleOrDefault(x => x.Email == credentials.Email); if (user != null) { return(InternalServerError(new InvalidOperationException("This email has already taken!"))); } user = new User { Email = credentials.Email, Password = credentials.Password }; user.Ticket = Guid.NewGuid().ToString(); ctx.Users.Add(user); ctx.SaveChanges(); string apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY"); SendGridAPIClient mc = new SendGridAPIClient(apiKey); Email to = new Email(user.Email); Email from = new Email("*****@*****.**"); string subject = "Welocme to Chatty!"; Content content = new Content("text/plain", String.Format("Hi {0},\n\nYou registration on Chatty is almost complete. Please click on this link to confirm your registration!\n\n{1}", user.Email.Split('@')[0], String.Format("https://chatty-api.azurewebsites.net/users/confirm?ticket={0}", user.Ticket))); Mail mail = new Mail(from, subject, to, content); dynamic response = await mc.client.mail.send.post(requestBody : mail.Get()); return(Ok(Dto.Wrap(new Poco.User { UserId = user.UserId, Email = user.Email, AuthAccessToken = null, AuthExpirationDate = null }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult SendMessage(Poco.Message message) { if (string.IsNullOrWhiteSpace(message.Sender)) { return(BadRequest("The sender is not valid!")); } if (string.IsNullOrWhiteSpace(message.Content)) { return(BadRequest("The password is not valid!")); } try { using (var ctx = new ChattyDbContext()) { string email = (this.User as ClaimsPrincipal).FindFirst(ClaimTypes.Email).Value; User user = ctx.Users.Single(x => x.Email == email); user.LastActiveDate = DateTime.Now.ToUniversalTime(); Message m = new Message { Content = message.Content, Sender = message.Sender, SendDate = DateTime.Now.ToUniversalTime() }; ctx.Messages.Add(m); ctx.SaveChanges(); _nhclient.SendGcmNativeNotificationAsync( Newtonsoft.Json.JsonConvert.SerializeObject(Push.Android.Make( "New messages", "You have new unread messages!", 1, m.MessageId.ToString() )), String.Concat("!", user.Email)); _nhclient.SendAppleNativeNotificationAsync( Newtonsoft.Json.JsonConvert.SerializeObject(Push.iOS.Make( "New messages", "You have new unread messages!", 1, m.MessageId.ToString() )), String.Concat("!", user.Email)); return(Ok(Dto.Wrap(new Poco.Message { MessageId = m.MessageId, Content = m.Content, Sender = m.Sender, SendDate = m.SendDate }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult LoginUser(Poco.User credentials) { if (string.IsNullOrWhiteSpace(credentials.Email)) { return(BadRequest("The email is not valid!")); } if (string.IsNullOrWhiteSpace(credentials.Password)) { return(BadRequest("The password is not valid!")); } try { using (var ctx = new ListyDbContext()) { User user = ctx.Users.SingleOrDefault(x => x.Email == credentials.Email); if (user == null) { return(Unauthorized()); } if (!user.IsConfirmed) { return(InternalServerError(new InvalidOperationException("You must confirm your email first!"))); } string p1 = FormsAuthentication.HashPasswordForStoringInConfigFile(user.Password, "MD5"); string p2 = FormsAuthentication.HashPasswordForStoringInConfigFile(credentials.Password, "MD5"); if (p1 != p2) { return(Unauthorized()); } var token = GetAuthenticationTokenForUser(user.Email); user.LoginDate = DateTime.Now.ToUniversalTime(); user.LastActiveDate = user.LoginDate; user.AuthAccessToken = token.RawData; user.AuthExpirationDate = token.ValidTo; ctx.SaveChanges(); return(Ok(Dto.Wrap(new Poco.User { UserId = user.UserId, Email = user.Email, LoginDate = user.LoginDate, AuthAccessToken = user.AuthAccessToken, AuthExpirationDate = user.AuthExpirationDate }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult Update(Poco.Issue item) { if (item.IssueId <= 0) { return(BadRequest("Issue ID is not valid!")); } if (String.IsNullOrWhiteSpace(item.Title)) { return(BadRequest("Title is not valid!")); } if (String.IsNullOrWhiteSpace(item.Description)) { return(BadRequest("Description is not valid!")); } try { using (var ctx = new BugghyDbContext()) { Issue ix = ctx.Issues.SingleOrDefault(x => x.IssueId == item.IssueId); if (ix == null) { return(InternalServerError(new InvalidOperationException("Invalid Issue ID!"))); } ix.Title = item.Title; ix.Description = item.Description; ctx.SaveChanges(); return(Ok(Dto.Wrap(new Poco.Issue { IssueId = ix.IssueId, GimmickId = ix.GimmickId, UserId = ix.UserId, Sender = ix.Sender, Code = ix.Code, Title = ix.Title, Description = ix.Description, Type = ix.Type, Status = ix.Status, CreationDate = ix.CreationDate, ReplyDate = ix.ReplyDate, ClosedDate = ix.ClosedDate, IsClosed = ix.IsClosed }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult Update(Poco.Gimmick item) { if (item.GimmickId <= 0) { return(BadRequest("Gimmick ID is not valid!")); } if (String.IsNullOrWhiteSpace(item.Name)) { return(BadRequest("Name is not valid!")); } if (String.IsNullOrWhiteSpace(item.Owner)) { return(BadRequest("Owner is not valid!")); } try { using (var ctx = new BugghyDbContext()) { Gimmick gi = ctx.Gimmicks.SingleOrDefault(x => x.GimmickId == item.GimmickId); if (gi == null) { return(InternalServerError(new InvalidOperationException("Invalid Gimmick ID!"))); } gi.Name = item.Name; gi.Description = item.Description; gi.Owner = item.Owner; ctx.SaveChanges(); return(Ok(Dto.Wrap(new Poco.Gimmick { GimmickId = gi.GimmickId, Name = gi.Name, Description = gi.Description, Owner = gi.Owner, ImageUrl = gi.ImageUrl, CreationDate = gi.CreationDate }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult Update(Poco.TodoItem item) { if (item.TodoItemId <= 0) { return(BadRequest("TodoItem ID is not valid!")); } if (String.IsNullOrWhiteSpace(item.Title)) { return(BadRequest("Title is not valid!")); } try { using (var ctx = new ListyDbContext()) { TodoItem ti = ctx.TodoItems.SingleOrDefault(x => x.TodoItemId == item.TodoItemId); if (item == null) { return(InternalServerError(new InvalidOperationException("Invalid TodoItem ID or User ID!"))); } ti.Title = item.Title; ti.Description = item.Description; ti.WillDoIn = item.WillDoIn; ti.Tags = item.Tags; ctx.SaveChanges(); return(Ok(Dto.Wrap(new Poco.TodoItem { TodoItemId = ti.TodoItemId, UserId = ti.UserId, Title = ti.Title, Description = ti.Description, CreationDate = ti.CreationDate, WillDoIn = ti.WillDoIn, Tags = ti.Tags, IsComplete = ti.IsComplete, CompletionDate = ti.CompletionDate }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult AddNew(Poco.TodoItem item) { if (item.UserId <= 0) { return(BadRequest("User ID is not valid!")); } if (String.IsNullOrWhiteSpace(item.Title)) { return(BadRequest("Title is not valid!")); } try { using (var ctx = new ListyDbContext()) { TodoItem ti = new TodoItem { UserId = item.UserId, Title = item.Title, Description = item.Description, CreationDate = DateTime.Now.ToUniversalTime(), WillDoIn = item.WillDoIn, Tags = item.Tags }; ctx.TodoItems.Add(ti); ctx.SaveChanges(); return(Ok(Dto.Wrap(new Poco.TodoItem { TodoItemId = ti.TodoItemId, UserId = ti.UserId, Title = ti.Title, Description = ti.Description, CreationDate = ti.CreationDate, WillDoIn = ti.WillDoIn, Tags = ti.Tags }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult GetMessages(int issueId = 0, int userId = 0) { if (issueId < 0) { return(BadRequest("Issue ID is not valid!")); } if (userId < 0) { return(BadRequest("Gimmick ID is not valid!")); } try { using (var ctx = new BugghyDbContext()) { var query = ctx.Messages.AsQueryable(); if (issueId > 0) { query = query.Where(x => x.IssueId == issueId); } if (userId > 0) { query = query.Where(x => x.UserId == userId); } return(Ok(Dto.Wrap(new Poco.DataBundle <Poco.Message> { Items = query .Select(x => new Poco.Message { MessageId = x.MessageId, IssueId = x.IssueId, UserId = x.UserId, Sender = x.Sender, Content = x.Content, PostDate = x.PostDate }) .ToArray() }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult AddNew(Poco.Gimmick item) { if (String.IsNullOrWhiteSpace(item.Name)) { return(BadRequest("Name is not valid!")); } if (String.IsNullOrWhiteSpace(item.Owner)) { return(BadRequest("Owner is not valid!")); } try { using (var ctx = new BugghyDbContext()) { Gimmick gi = new Gimmick { Name = item.Name, Description = item.Description, Owner = item.Owner, CreationDate = DateTime.Now.ToUniversalTime() }; ctx.Gimmicks.Add(gi); ctx.SaveChanges(); return(Ok(Dto.Wrap(new Poco.Gimmick { GimmickId = gi.GimmickId, Name = gi.Name, Description = gi.Description, Owner = gi.Owner, ImageUrl = gi.ImageUrl, CreationDate = gi.CreationDate }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult GetMyList(int userId) { if (userId <= 0) { return(BadRequest("User ID is not valid!")); } try { using (var ctx = new ListyDbContext()) { User user = ctx.Users.SingleOrDefault(x => x.UserId == userId); if (user == null) { return(InternalServerError(new InvalidOperationException("The User ID you provide is invalid!"))); } return(Ok(Dto.Wrap(new Poco.WorkList { Items = ctx.TodoItems .Where(x => x.UserId == userId) .Select(x => new Poco.TodoItem { TodoItemId = x.TodoItemId, UserId = x.UserId, Title = x.Title, Description = x.Description, CreationDate = x.CreationDate, WillDoIn = x.WillDoIn, Tags = x.Tags, IsComplete = x.IsComplete, CompletionDate = x.CompletionDate }) .ToArray() }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult Uncomplete([FromBody] int itemId) { if (itemId <= 0) { return(BadRequest("TodoItem ID is not valid!")); } try { using (var ctx = new ListyDbContext()) { TodoItem ti = ctx.TodoItems.SingleOrDefault(x => x.TodoItemId == itemId); if (ti == null) { return(InternalServerError(new InvalidOperationException("Invalid TodoItem ID!"))); } ti.IsComplete = false; ti.CompletionDate = null; ctx.SaveChanges(); return(Ok(Dto.Wrap(new Poco.TodoItem { TodoItemId = ti.TodoItemId, UserId = ti.UserId, Title = ti.Title, Description = ti.Description, CreationDate = ti.CreationDate, WillDoIn = ti.WillDoIn, Tags = ti.Tags, IsComplete = ti.IsComplete, CompletionDate = ti.CompletionDate }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult GetNewMessages(int lastMessageId, string me) { if (lastMessageId == 0) { return(InternalServerError(new InvalidOperationException("Invalid message Id"))); } try { using (var ctx = new ChattyDbContext()) { string email = (this.User as ClaimsPrincipal).FindFirst(ClaimTypes.Email).Value; User user = ctx.Users.Single(x => x.Email == email); user.LastActiveDate = DateTime.Now.ToUniversalTime(); ctx.SaveChanges(); if (lastMessageId > ctx.Messages.OrderByDescending(x => x.MessageId).Take(1).ToList().FirstOrDefault()?.MessageId) { return(InternalServerError(new InvalidOperationException("Invalid message Id"))); } return(Ok(Dto.Wrap(new Poco.Bulk { Messages = ctx.Messages .Where(x => x.Sender != me && x.MessageId >= lastMessageId) .Select(x => new Poco.Message { MessageId = x.MessageId, Content = x.Content, Sender = x.Sender, SendDate = x.SendDate }) .ToArray() }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult RestoreUser(string accessToken) { if (string.IsNullOrWhiteSpace(accessToken)) { return(BadRequest("The access token is not valid!")); } try { using (var ctx = new BugghyDbContext()) { User user = ctx.Users.SingleOrDefault(x => x.AuthAccessToken == accessToken); if (user == null) { return(Unauthorized()); } user.LoginDate = DateTime.Now.ToUniversalTime(); user.LastActiveDate = user.LoginDate; ctx.SaveChanges(); return(Ok(Dto.Wrap(new Poco.User { UserId = user.UserId, Email = user.Email, LoginDate = user.LoginDate, AuthAccessToken = user.AuthAccessToken, AuthExpirationDate = user.AuthExpirationDate }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public async Task <IHttpActionResult> LoginUser(Facebook.Credentials credentials) { if (string.IsNullOrWhiteSpace(credentials.UserId)) { return(BadRequest("The Facebook User ID is not valid!")); } if (string.IsNullOrWhiteSpace(credentials.Email)) { return(BadRequest("The email is not valid!")); } if (string.IsNullOrWhiteSpace(credentials.Token)) { return(BadRequest("The Facebook token is not valid!")); } try { RestClient c = new RestClient(new Uri("https://graph.facebook.com/")); // To login via facebook token, we need first to validate the token passed // To validate the token we must check if it belongs to our FB application // Reference: http://stackoverflow.com/questions/5406859/facebook-access-token-server-side-validation-for-iphone-app // Access token request RestRequest tr = new RestRequest("oauth/access_token", Method.GET); tr.AddParameter("client_id", ConfigurationManager.AppSettings["FB_APP_ID"]); tr.AddParameter("client_secret", ConfigurationManager.AppSettings["FB_APP_SECRET"]); tr.AddParameter("grant_type", "client_credentials"); var r1 = await c.ExecuteTaskAsync(tr); if (r1.StatusCode != HttpStatusCode.OK) { return(InternalServerError(new InvalidOperationException("Unable to login via Facebook"))); } if (String.IsNullOrWhiteSpace(r1.Content) || !r1.Content.Contains("access_token=")) { return(InternalServerError(new InvalidOperationException("Unable to login via Facebook"))); } string accessToken = r1.Content.Split('=')[1]; // Validation request RestRequest vr = new RestRequest("debug_token", Method.GET); vr.AddParameter("input_token", credentials.Token); vr.AddParameter("access_token", accessToken); var r2 = await c.ExecuteTaskAsync <Facebook.DebugToken>(vr); if (r2.StatusCode != HttpStatusCode.OK) { return(InternalServerError(new InvalidOperationException("Unable to login via Facebook"))); } if (r2.Data.data.app_id != ConfigurationManager.AppSettings["FB_APP_ID"] || r2.Data.data.user_id != credentials.UserId || !r2.Data.data.is_valid) { return(InternalServerError(new InvalidOperationException("Unable to login via Facebook"))); } using (var ctx = new ChattyDbContext()) { // Check if we have already registered the user, if not this login method will take care of it User user = ctx.Users.SingleOrDefault(x => x.Email == credentials.Email); if (user == null) { user = new User { FacebookId = credentials.UserId, Email = credentials.Email, Password = null, Ticket = Guid.NewGuid().ToString(), IsConfirmed = true }; ctx.Users.Add(user); ctx.SaveChanges(); } else { user.FacebookId = credentials.UserId; user.IsConfirmed = true; ctx.SaveChanges(); } int activeUsers = ctx.Users.Count(x => x.LastActiveDate.HasValue && DbFunctions.DiffDays(DateTime.Now, x.AuthExpirationDate.Value) < UsersController.AUTH_TOKEN_MAX_DURATION); if (activeUsers == USERS_MAX_LOGGED) { // Check if we can kick out a user marked as not active User userToKick = ctx.Users .Where(x => x.LastActiveDate.HasValue) .Where(x => DbFunctions.DiffMinutes(DateTime.Now, x.LastActiveDate.Value) >= USERS_MAX_INACTIVE_TIME) .OrderBy(x => x.LastActiveDate.GetValueOrDefault()) .SingleOrDefault(); // We got a candidate? if (userToKick != null) { userToKick.LoginDate = null; userToKick.LastActiveDate = null; userToKick.AuthAccessToken = null; userToKick.AuthExpirationDate = null; } else { return(InternalServerError(new InvalidOperationException("Max user logged reached. Please retry later!"))); } } var token = GetAuthenticationTokenForUser(user.Email); user.LoginDate = DateTime.Now.ToUniversalTime(); user.LastActiveDate = user.LoginDate; user.AuthAccessToken = token.RawData; user.AuthExpirationDate = token.ValidTo; ctx.SaveChanges(); await _nhclient.SendGcmNativeNotificationAsync( Newtonsoft.Json.JsonConvert.SerializeObject(Push.Android.Make( "New user connected", String.Format("User {0} has joined the chat.", credentials.Email.Split('@')[0]), 2, credentials.Email.Split('@')[0] )), String.Concat("!", user.Email)); await _nhclient.SendAppleNativeNotificationAsync( Newtonsoft.Json.JsonConvert.SerializeObject(Push.iOS.Make( "New user connected", String.Format("User {0} has joined the chat.", credentials.Email.Split('@')[0]), 2, credentials.Email.Split('@')[0] )), String.Concat("!", user.Email)); return(Ok(Dto.Wrap(new Poco.User { UserId = user.UserId, Email = user.Email, LoginDate = user.LoginDate, AuthAccessToken = user.AuthAccessToken, AuthExpirationDate = user.AuthExpirationDate }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult LoginUser(Poco.User credentials) { if (string.IsNullOrWhiteSpace(credentials.Email)) { return(BadRequest("The email is not valid!")); } if (string.IsNullOrWhiteSpace(credentials.Password)) { return(BadRequest("The password is not valid!")); } try { using (var ctx = new ChattyDbContext()) { User user = ctx.Users.SingleOrDefault(x => x.Email == credentials.Email); if (user == null) { return(Unauthorized()); } if (!user.IsConfirmed) { return(InternalServerError(new InvalidOperationException("You must confirm your email first!"))); } if (!String.IsNullOrWhiteSpace(user.FacebookId) && user.Password == null) { return(InternalServerError(new InvalidOperationException("You must login via Facebook!"))); } string p1 = FormsAuthentication.HashPasswordForStoringInConfigFile(user.Password, "MD5"); string p2 = FormsAuthentication.HashPasswordForStoringInConfigFile(credentials.Password, "MD5"); if (p1 != p2) { return(Unauthorized()); } int activeUsers = ctx.Users.Count(x => x.LastActiveDate.HasValue && DbFunctions.DiffDays(DateTime.Now, x.AuthExpirationDate.Value) < UsersController.AUTH_TOKEN_MAX_DURATION); if (activeUsers == USERS_MAX_LOGGED) { // Check if we can kick out a user marked as not active User userToKick = ctx.Users .Where(x => x.LastActiveDate.HasValue) .Where(x => DbFunctions.DiffMinutes(DateTime.Now, x.LastActiveDate.Value) >= USERS_MAX_INACTIVE_TIME) .OrderBy(x => x.LastActiveDate.GetValueOrDefault()) .SingleOrDefault(); // We got a candidate? if (userToKick != null) { userToKick.LoginDate = null; userToKick.LastActiveDate = null; userToKick.AuthAccessToken = null; userToKick.AuthExpirationDate = null; } else { return(InternalServerError(new InvalidOperationException("Max user logged reached. Please retry later!"))); } } var token = GetAuthenticationTokenForUser(user.Email); user.LoginDate = DateTime.Now.ToUniversalTime(); user.LastActiveDate = user.LoginDate; user.AuthAccessToken = token.RawData; user.AuthExpirationDate = token.ValidTo; ctx.SaveChanges(); _nhclient.SendGcmNativeNotificationAsync( Newtonsoft.Json.JsonConvert.SerializeObject(Push.Android.Make( "New user connected", String.Format("User {0} has joined the chat.", credentials.Email.Split('@')[0]), 2, credentials.Email.Split('@')[0] )), String.Concat("!", user.Email)); _nhclient.SendAppleNativeNotificationAsync( Newtonsoft.Json.JsonConvert.SerializeObject(Push.iOS.Make( "New user connected", String.Format("User {0} has joined the chat.", credentials.Email.Split('@')[0]), 2, credentials.Email.Split('@')[0] )), String.Concat("!", user.Email)); return(Ok(Dto.Wrap(new Poco.User { UserId = user.UserId, Email = user.Email, LoginDate = user.LoginDate, AuthAccessToken = user.AuthAccessToken, AuthExpirationDate = user.AuthExpirationDate }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult GetIssues(int gimmickId = 0, int userId = 0, IssueType type = IssueType.Any, IssueStatus status = IssueStatus.Any) { if (gimmickId < 0) { return(BadRequest("Gimmick ID is not valid!")); } if (userId < 0) { return(BadRequest("Gimmick ID is not valid!")); } try { using (var ctx = new BugghyDbContext()) { var query = ctx.Issues.AsQueryable(); if (gimmickId > 0) { query = query.Where(x => x.GimmickId == gimmickId); } if (userId > 0) { query = query.Where(x => x.UserId == userId); } if (type != IssueType.Any) { query = query.Where(x => x.Type == type); } if (status != IssueStatus.Any) { query = query.Where(x => x.Status == status); } return(Ok(Dto.Wrap(new Poco.DataBundle <Poco.Issue> { Items = query .Select(x => new Poco.Issue { IssueId = x.IssueId, GimmickId = x.GimmickId, UserId = x.UserId, Sender = x.Sender, Code = x.Code, Title = x.Title, Description = x.Description, Type = x.Type, Status = x.Status, CreationDate = x.CreationDate, ReplyDate = x.ReplyDate, ClosedDate = x.ClosedDate, IsClosed = x.IsClosed }) .ToArray() }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult AddNew(Poco.Issue item) { if (item.GimmickId <= 0) { return(BadRequest("Gimmick ID is not valid!")); } if (item.UserId <= 0) { return(BadRequest("User ID is not valid!")); } if (String.IsNullOrWhiteSpace(item.Title)) { return(BadRequest("Title is not valid!")); } if (String.IsNullOrWhiteSpace(item.Description)) { return(BadRequest("Description is not valid!")); } try { using (var ctx = new BugghyDbContext()) { User user = ctx.Users.SingleOrDefault(x => x.UserId == item.UserId); if (user == null) { throw new InvalidOperationException("Unable to find an user with the ID specified!"); } Issue ix = new Issue { GimmickId = item.GimmickId, UserId = item.UserId, Sender = user.Email, Title = item.Title, Description = item.Description, Type = item.Type, Status = IssueStatus.Opened, CreationDate = DateTime.Now.ToUniversalTime() }; ctx.Issues.Add(ix); ctx.SaveChanges(); // Updating code ix.Code = String.Concat( ix.Type.ToString().Substring(0, 1), "-", ix.IssueId.ToString()); ctx.SaveChanges(); return(Ok(Dto.Wrap(new Poco.Issue { IssueId = ix.IssueId, GimmickId = ix.GimmickId, UserId = ix.UserId, Sender = ix.Sender, Code = ix.Code, Title = ix.Title, Description = ix.Description, Type = ix.Type, Status = ix.Status, CreationDate = ix.CreationDate, ReplyDate = ix.ReplyDate, ClosedDate = ix.ClosedDate, IsClosed = ix.IsClosed }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult RestoreUser(string accessToken) { if (string.IsNullOrWhiteSpace(accessToken)) { return(BadRequest("The access token is not valid!")); } try { using (var ctx = new ChattyDbContext()) { User user = ctx.Users.SingleOrDefault(x => x.AuthAccessToken == accessToken); if (user == null) { return(Unauthorized()); } int activeUsers = ctx.Users.Count(x => x.LastActiveDate.HasValue && DbFunctions.DiffDays(DateTime.Now, x.AuthExpirationDate.Value) < UsersController.AUTH_TOKEN_MAX_DURATION); if (activeUsers == USERS_MAX_LOGGED) { // Check if we can kick out a user marked as not active User userToKick = ctx.Users .Where(x => x.LastActiveDate.HasValue) .Where(x => DbFunctions.DiffMinutes(DateTime.Now, x.LastActiveDate.Value) >= USERS_MAX_INACTIVE_TIME) .OrderBy(x => x.LastActiveDate.GetValueOrDefault()) .SingleOrDefault(); // We got a candidate? if (userToKick != null) { userToKick.LoginDate = null; userToKick.LastActiveDate = null; userToKick.AuthAccessToken = null; userToKick.AuthExpirationDate = null; } else { return(InternalServerError(new InvalidOperationException("Max user logged reached. Please retry later!"))); } } user.LoginDate = DateTime.Now.ToUniversalTime(); user.LastActiveDate = user.LoginDate; ctx.SaveChanges(); _nhclient.SendGcmNativeNotificationAsync( Newtonsoft.Json.JsonConvert.SerializeObject(Push.Android.Make( "New user connected", String.Format("User {0} has joined the chat.", user.Email.Split('@')[0]), 2, user.Email.Split('@')[0] )), String.Concat("!", user.Email)); _nhclient.SendAppleNativeNotificationAsync( Newtonsoft.Json.JsonConvert.SerializeObject(Push.iOS.Make( "New user connected", String.Format("User {0} has joined the chat.", user.Email.Split('@')[0]), 2, user.Email.Split('@')[0] )), String.Concat("!", user.Email)); return(Ok(Dto.Wrap(new Poco.User { UserId = user.UserId, Email = user.Email, LoginDate = user.LoginDate, AuthAccessToken = user.AuthAccessToken, AuthExpirationDate = user.AuthExpirationDate }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public IHttpActionResult Post(Poco.Message item) { if (item.IssueId <= 0) { return(BadRequest("Issue ID is not valid!")); } if (item.UserId <= 0) { return(BadRequest("User ID is not valid!")); } if (String.IsNullOrWhiteSpace(item.Content)) { return(BadRequest("Title is not valid!")); } try { using (var ctx = new BugghyDbContext()) { User user = ctx.Users.SingleOrDefault(x => x.UserId == item.UserId); if (user == null) { throw new InvalidOperationException("Unable to find an user with the ID specified!"); } Issue issue = ctx.Issues.SingleOrDefault(x => x.IssueId == item.IssueId); if (issue == null) { throw new InvalidOperationException("Unable to find an issue with the ID specified!"); } // Update reply date issue.ReplyDate = DateTime.Now.ToUniversalTime(); Message me = new Message { IssueId = item.IssueId, UserId = item.UserId, Sender = user.Email, Content = item.Content, PostDate = DateTime.Now.ToUniversalTime() }; ctx.Messages.Add(me); ctx.SaveChanges(); return(Ok(Dto.Wrap(new Poco.Message { MessageId = me.MessageId, IssueId = me.IssueId, UserId = me.UserId, Sender = me.Sender, Content = me.Content, PostDate = me.PostDate }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }
public async Task <IHttpActionResult> LoginUser(Google.Credentials credentials) { if (string.IsNullOrWhiteSpace(credentials.ClientID)) { return(BadRequest("The Google client ID is not valid!")); } if (string.IsNullOrWhiteSpace(credentials.Email)) { return(BadRequest("The email is not valid!")); } if (string.IsNullOrWhiteSpace(credentials.Token)) { return(BadRequest("The Google token is not valid!")); } try { RestClient c = new RestClient(new Uri("https://www.googleapis.com")); // To login via google token, we need first to validate the token passed // To validate the token we must check if it belongs to our Google application // Reference: https://developers.google.com/identity/sign-in/android/backend-auth // Validation request RestRequest vr = new RestRequest("oauth2/v3/tokeninfo", Method.GET); vr.AddParameter("id_token", credentials.Token); var r = await c.ExecuteTaskAsync <Google.TokenClaims>(vr); if (r.StatusCode != HttpStatusCode.OK) { return(InternalServerError(new InvalidOperationException("Unable to login via Google"))); } if (r.Data.aud != credentials.ClientID || r.Data.email != credentials.Email || r.Data.email_verified == false) { return(InternalServerError(new InvalidOperationException("Unable to login via Google"))); } using (var ctx = new BugghyDbContext()) { // Check if we have already registered the user, if not this login method will take care of it User user = ctx.Users.SingleOrDefault(x => x.Email == credentials.Email); if (user == null) { user = new User { GoogleId = r.Data.sub, Email = credentials.Email, Password = null, Ticket = Guid.NewGuid().ToString(), IsConfirmed = true }; ctx.Users.Add(user); ctx.SaveChanges(); } else { user.GoogleId = r.Data.sub; user.IsConfirmed = true; ctx.SaveChanges(); } var token = GetAuthenticationTokenForUser(user.Email); user.LoginDate = DateTime.Now.ToUniversalTime(); user.LastActiveDate = user.LoginDate; user.AuthAccessToken = token.RawData; user.AuthExpirationDate = token.ValidTo; ctx.SaveChanges(); return(Ok(Dto.Wrap(new Poco.User { UserId = user.UserId, Email = user.Email, LoginDate = user.LoginDate, AuthAccessToken = user.AuthAccessToken, AuthExpirationDate = user.AuthExpirationDate }))); } } catch (Exception ex) { return(InternalServerError(ex)); } }