public void Patch_DataCorrect_BoardUpdated() { var browser = new Browser(new DefaultNancyBootstrapper()); var me = UserFaker.Create(); var boardColumn = BoardColumnFaker.Create(me); var updatedName = "updatedName_" + Rand.SmallInt(); var updatedBoardOrder = Convert.ToString(Rand.IntRange(0, 40)); var result = browser.Patch("/api/v1/board_column/edit", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(me.id)); with.Query("board_column_guid", boardColumn.guid); with.Query("name", updatedName); with.Query("board_order", updatedBoardOrder); }).Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); var json = JObject.Parse(result.Body.AsString()); Assert.AreEqual(boardColumn.guid, json["data"]["board_column"].Value <string>("guid")); Assert.AreEqual(updatedName, json["data"]["board_column"].Value <string>("name")); Assert.AreEqual(updatedBoardOrder, json["data"]["board_column"].Value <string>("board_order")); }
public void Create_DataCorrect_BoardCreated() { var creator = UserFaker.Create(); var project = ProjectFaker.Create(creator); var browser = new Browser(new DefaultNancyBootstrapper()); var boardTitle = "testBoard" + Rand.SmallInt(); var boardDescription = "testDescription" + Rand.SmallInt(); var result = browser.Post("/api/v1/board/create", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(creator.id)); with.Query("name", boardTitle); with.Query("description", boardDescription); with.Query("creator_guid", creator.guid); with.Query("project_guid", project.guid); }).Result; Assert.AreEqual(HttpStatusCode.Created, result.StatusCode); var json = JObject.Parse(result.Body.AsString()); var guid = json["data"]["board"].Value<string>("guid") ?? ""; var createdBoard = BoardRepository.FindByGuid(guid); Assert.NotNull(createdBoard); Assert.AreEqual(boardTitle, createdBoard.name); Assert.AreEqual(boardDescription, createdBoard.description); Assert.AreEqual( createdBoard.guid, json["data"]["board"].Value<string>("guid") ?? "" ); }
public JwtAuthController() { Get("/api/v1/login", _ => { var email = (string)Request.Query["email"]; var password = (string)Request.Query["password"]; var user = UserRepository.FindByEmail(email); if (user == null) { return(HttpResponse.Error(HttpStatusCode.NotFound, "User not found")); } if (Encryptor.Encrypt(password) != user.password) { return(HttpResponse.Error( new HttpError(HttpStatusCode.Unauthorized, "Your email / password combination is incorrect") )); } return(HttpResponse.Data(new JObject() { ["token"] = Jwt.FromUserId(user.id) })); }); }
public void Create_DataCorrect_BoardColumnCreated() { var user = UserFaker.Create(); var board = BoardFaker.Create(user); var browser = new Browser(new DefaultNancyBootstrapper()); var boardColumnTitle = "testBoard" + Rand.SmallInt(); var boardOrder = Convert.ToString(Rand.IntRange(0, 25)); var result = browser.Post("/api/v1/board_column/create", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); with.Query("name", boardColumnTitle); with.Query("board_guid", board.guid); with.Query("board_order", boardOrder); }).Result; Assert.AreEqual(HttpStatusCode.Created, result.StatusCode); var json = JObject.Parse(result.Body.AsString()); var guid = json["data"]["board_column"].Value <string>("guid") ?? ""; var createdBoardColumn = BoardColumnRepository.FindByGuid(guid); Assert.NotNull(createdBoardColumn); Assert.AreEqual(boardColumnTitle, createdBoardColumn.name); Assert.AreEqual(boardOrder, Convert.ToString(createdBoardColumn.board_order)); Assert.AreEqual( createdBoardColumn.guid, json["data"]["board_column"].Value <string>("guid") ?? "" ); }
public void Edit_DataCorrect_StatusUpdated() { var user = UserFaker.Create(); var decision = EntityDecisionFaker.Create(user); Assert.AreEqual(DecisionStatus.Open, decision.status); Assert.NotNull(decision); var result = new Browser(new DefaultNancyBootstrapper()) .Patch("/api/v1/entity/decision/edit", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); with.Query("decision_guid", decision.guid); with.Query("new_status", DecisionStatus.Canceled.ToString()); }).Result; var body = JObject.Parse(result.Body.AsString()); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); Assert.IsNotEmpty(body["data"]["decision"].ToString()); decision = decision.Refresh(); Assert.AreEqual(DecisionStatus.Canceled, decision.status); }
public void Create_DataCorrect_RepoCreated() { var user = UserFaker.Create(); var browser = new Browser(new DefaultNancyBootstrapper()); var repoTitle = "testRepo" + Rand.SmallInt(); var result = browser.Post("/api/v1/repository/create", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); with.Query("title", repoTitle); with.Query("repo_url", "randomUrl" + Rand.SmallInt()); with.Query("service_type", RepoServiceType.GitHub.ToString()); }).Result; Assert.AreEqual(HttpStatusCode.Created, result.StatusCode); var json = JObject.Parse(result.Body.AsString()); var guid = json["data"]["repository"].Value <string>("guid") ?? ""; var createdRepository = RepoRepository.FindByGuid(guid); Assert.NotNull(createdRepository); Assert.AreEqual(repoTitle, createdRepository.title); Assert.AreEqual( user.guid, json["data"]["repository"]["creator"].Value <string>("guid") ?? "" ); }
public void Create_DataCorrect_InvoiceCreated() { var user = UserFaker.Create(); var project = ProjectFaker.Create(); var amount = Rand.SmallDecimal(); CurrencyWalletFaker.Create(CurrencyType.BitCoin); var result = new Browser(new DefaultNancyBootstrapper()) .Post("/api/v1/invoice/new", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); with.Query("entity_guid", project.guid); with.Query("entity_type", EntityType.Project.ToString()); with.Query("amount", amount.ToString(CultureInfo.InvariantCulture)); with.Query("currency_type", CurrencyType.BitCoin.ToString()); }).Result; Assert.AreEqual(1, global::App.DL.Model.Funding.Invoice.GetActiveForUser(user).Length); Assert.AreEqual(HttpStatusCode.Created, result.StatusCode); var jsonData = JObject.Parse(result.Body.AsString())["data"]["invoice"]; Assert.AreEqual(project.guid, jsonData.Value <string>("entity_guid") ?? ""); Assert.AreEqual(amount, jsonData.Value <decimal?>("amount") ?? 0); }
public void Patch_DataCorrect_RepositoryUpdated() { var browser = new Browser(new DefaultNancyBootstrapper()); var repo = RepoFaker.Create(); var updatedTitle = "updatedTitle_" + Rand.SmallInt(); var updatedRepoUrl = "https://github.com/someuser/repo_" + Rand.SmallInt(); var result = browser.Patch("/api/v1/repository/edit", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(UserFaker.Create().id)); with.Query("repo_guid", repo.guid); with.Query("title", updatedTitle); with.Query("repo_url", updatedRepoUrl); }).Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); var json = JObject.Parse(result.Body.AsString()); Assert.AreEqual(repo.guid, json["data"]["repository"].Value <string>("guid")); Assert.AreEqual(updatedTitle, json["data"]["repository"].Value <string>("title")); Assert.AreEqual(updatedRepoUrl, json["data"]["repository"].Value <string>("repo_url")); }
public void Create_DataCorrect_CardCreated() { var user = UserFaker.Create(); var column = BoardColumnFaker.Create(user); var browser = new Browser(new DefaultNancyBootstrapper()); var cardTitle = "testCard" + Rand.SmallInt(); var description = "descriptionCard" + Rand.SmallInt(); var columnOrder = Convert.ToString(Rand.IntRange(1, 25)); var result = browser.Post("/api/v1/card/create", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); with.Query("name", cardTitle); with.Query("description", description); with.Query("column_guid", column.guid); with.Query("column_order", columnOrder); with.Query("creator_guid", user.guid); }).Result; Assert.AreEqual(HttpStatusCode.Created, result.StatusCode); var json = JObject.Parse(result.Body.AsString()); var guid = json["data"]["card"].Value <string>("guid") ?? ""; var createdCard = CardRepository.FindByGuid(guid); Assert.NotNull(createdCard); Assert.AreEqual(cardTitle, createdCard.name); Assert.AreEqual(columnOrder, Convert.ToString(createdCard.column_order)); Assert.AreEqual( createdCard.guid, json["data"]["card"].Value <string>("guid") ?? "" ); }
public void Create_DataCorrect_DecisionCreated() { var user = UserFaker.Create(); var project = ProjectFaker.Create(); var result = new Browser(new DefaultNancyBootstrapper()) .Post("/api/v1/entity/decision/create", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); with.Query("entity_guid", project.guid); with.Query("entity_type", EntityType.Project.ToString()); with.Query("title", "test title"); with.Query("content", "test content here and longer than 10 characters"); with.Query("deadline", DateTime.Now.AddDays(2).ToString(CultureInfo.InvariantCulture)); with.Query("options", "['option a', 'option b']"); }).Result; var body = JObject.Parse(result.Body.AsString()); Assert.AreEqual(HttpStatusCode.Created, result.StatusCode); Assert.IsNotEmpty(body["data"]["decision"].ToString()); var decision = EntityDecisionRepository.FindByGuid(body["data"]["decision"].Value <string>("guid")); Assert.NotNull(decision); Assert.AreEqual(user.id, decision.creator_id); Assert.AreEqual(project.id, decision.entity_id); Assert.AreEqual(2, decision.Options().Length); }
public void Patch_DataCorrect_BoardUpdated() { var browser = new Browser(new DefaultNancyBootstrapper()); var me = UserFaker.Create(); var board = BoardFaker.Create(me); var updatedName = "updatedName_" + Rand.SmallInt(); var updatedDescription = "updatedDescription_" + Rand.SmallInt(); var result = browser.Patch("/api/v1/board/edit", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(me.id)); with.Query("board_guid", board.guid); with.Query("name", updatedName); with.Query("description", updatedDescription); }).Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); var json = JObject.Parse(result.Body.AsString()); Assert.AreEqual(board.guid, json["data"]["board"].Value<string>("guid")); Assert.AreEqual(updatedName, json["data"]["board"].Value<string>("name")); Assert.AreEqual(updatedDescription, json["data"]["board"].Value<string>("description")); }
public void FromUserId_DataCorrect_OkDecoded() { var userId = new Random().Next(1, 99999); var token = Jwt.FromUserId(userId); Assert.AreEqual(userId, Jwt.GetUserIdFromToken(token)); }
public GitlabAuthController() { var clientId = AppConfig.GetConfiguration("auth:external:gitlab:client_id"); var redirectUri = AppConfig.GetConfiguration("auth:external:gitlab:redirect_url"); Get("/api/v1/auth/gitlab/login_link/get", _ => { var loginLink = $"https://gitlab.com/oauth/authorize?client_id={clientId}&redirect_uri={redirectUri}" + $"&response_type=token&scope={Scopes}"; return(HttpResponse.Data(new JObject() { ["login_link"] = loginLink })); }); Get("/api/v1/auth/gitlab/get_auth_token", av => { var errors = ValidationProcessor.Process(Request, new IValidatorRule[] { new ShouldHaveParameters(new[] { "access_token" }), }); if (errors.Count > 0) { return(HttpResponse.Errors(errors)); } var accessToken = GetRequestStr("access_token"); var client = new GitLabClient(accessToken); client.SetAuthorizedUser(); if (client.User == null) { return(HttpResponse.Error(HttpStatusCode.Unauthorized, "We're unable to get your access token, please try again")); } var user = UserRepository.FindByEmail(client.User.Email) ?? UserRepository.FindOrCreateByEmailAndLogin( client.User.Email, client.User.Login, null, UserRepository.FindByGuid(GetRequestStr("referral_key")) ); ServiceAccessTokenRepository.FindOrUpdateAccessToken(user, accessToken, ServiceType.GitLab); return(HttpResponse.Data(new JObject() { ["token"] = Jwt.FromUserId(user.id) })); }); }
public void GetActive_DataCorrect_GotInvoices() { var user = UserFaker.Create(); InvoiceFaker.Create(user); var result = new Browser(new DefaultNancyBootstrapper()) .Get("/api/v1/me/invoices/active", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); }).Result; Assert.AreEqual(1, global::App.DL.Model.Funding.Invoice.GetActiveForUser(user).Length); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); }
public void Delete_DataCorrect_DecisionDeleted() { var user = UserFaker.Create(); var decision = EntityDecisionFaker.Create(user); var result = new Browser(new DefaultNancyBootstrapper()) .Delete("/api/v1/entity/decision/delete", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); with.Query("decision_guid", decision.guid); }).Result; JObject.Parse(result.Body.AsString()); Assert.IsNull(decision.Refresh()); }
public void Delete_DataCorrect_BoardDeleted() { var browser = new Browser(new DefaultNancyBootstrapper()); var me = UserFaker.Create(); var board = BoardFaker.Create(me); Assert.NotNull(BoardRepository.Find(board.id)); var result = browser.Delete("/api/v1/board/delete", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(me.id)); with.Query("board_guid", board.guid); }).Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); Assert.IsNull(BoardRepository.Find(board.id)); }
public void Edit_ChangingStatusOfOtherUsersInvoice_Forbidden() { var user = UserFaker.Create(); var invoice = InvoiceFaker.Create(); Assert.AreEqual(InvoiceStatus.Created, invoice.status); var result = new Browser(new DefaultNancyBootstrapper()) .Patch("/api/v1/me/invoice/status/update", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); with.Query("invoice_guid", invoice.guid); with.Query("status", InvoiceStatus.RequiresConfirmation.ToString()); }).Result; Assert.AreEqual(HttpStatusCode.Forbidden, result.StatusCode); Assert.AreEqual(InvoiceStatus.Created, invoice.Refresh().status); }
public FacebookAuthController() { Get("/api/v1/auth/facebook/my_token/get", _ => { var errors = ValidationProcessor.Process(Request, new IValidatorRule[] { new ShouldHaveParameters(new[] { "facebook_token" }), }); if (errors.Count > 0) { return(HttpResponse.Errors(errors)); } var facebookToken = GetRequestStr("facebook_token"); var response = new HttpClient().GetAsync( ApiUrl + $"me?access_token={facebookToken}&fields=name,email" ).Result; if (!response.IsSuccessStatusCode) { return(HttpResponse.Error(HttpStatusCode.BadRequest, "Invalid facebook token")); } var json = JObject.Parse(response.Content.ReadAsStringAsync().Result); var email = json.Value <string>("email"); var login = email.Split("@")[0]; var user = UserRepository.FindByEmail(email) ?? UserRepository.FindOrCreateByEmailAndLogin( email, login, null, UserRepository.FindByGuid(GetRequestStr("referral_key")) ); var accessToken = ServiceAccessTokenRepository.FindOrUpdateAccessToken(user, facebookToken, ServiceType.Facebook); accessToken.UpdateCol("origin_user_id", json.Value <string>("id")); return(HttpResponse.Data(new JObject() { ["token"] = Jwt.FromUserId(user.id) })); }); }
public void Delete_DataCorrect_RepositoryDeleted() { var browser = new Browser(new DefaultNancyBootstrapper()); var repo = RepoFaker.Create(); var result = browser.Delete("/api/v1/repository/delete", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(UserFaker.Create().id)); with.Query("repo_guid", repo.guid); }).Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); var json = JObject.Parse(result.Body.AsString()); Assert.AreEqual(repo.guid, json["data"]["repository"].Value <string>("guid")); Assert.IsNull(RepoRepository.FindByGuid(repo.guid)); }
public void Create_DataCorrect_ProjectTeamMemberCreated() { var user = UserFaker.Create(); var project = ProjectFaker.Create(user); var browser = new Browser(new DefaultNancyBootstrapper()); var result = browser.Post("/api/v1/project_team_member/create", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); with.Query("project_guid", project.guid); with.Query("user_guid", user.guid); }).Result; Assert.AreEqual(HttpStatusCode.Created, result.StatusCode); var createdTeamMember = ProjectTeamMemberRepository.Find(project, user); Assert.NotNull(createdTeamMember); Assert.AreEqual(project.id, createdTeamMember.project_id); Assert.AreEqual(user.id, createdTeamMember.user_id); }
public void Vote_DataCorrect_VoteRecorded() { var user = UserFaker.Create(); var decision = EntityDecisionFaker.Create(user); var option = EntityDecisionOptionFaker.Create(decision); Assert.IsNull(option.UserVote(user)); var result = new Browser(new DefaultNancyBootstrapper()) .Post("/api/v1/entity/decision/vote", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); with.Query("option_guid", option.guid); }).Result; JObject.Parse(result.Body.AsString()); Assert.NotNull(option.UserVote(user)); }
public void Patch_DataCorrect_ProjectUpdated() { var browser = new Browser(new DefaultNancyBootstrapper()); var project = ProjectFaker.Create(); var updatedDescription = "updatedDescription_" + Rand.SmallInt(); var result = browser.Patch("/api/v1/project/edit", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(UserFaker.Create().id)); with.Query("project_guid", project.guid); with.Query("description", updatedDescription); }).Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); var json = JObject.Parse(result.Body.AsString()); Assert.AreEqual(project.guid, json["data"]["project"].Value <string>("guid")); Assert.AreEqual(updatedDescription, json["data"]["project"].Value <string>("description")); }
public void Delete_DataCorrect_ProjectTeamMemberDeleted() { var browser = new Browser(new DefaultNancyBootstrapper()); var user = UserFaker.Create(); var teamMember = ProjectTeamMemberFaker.Create(); ProjectTeamMemberFaker.Create(teamMember.Project(), user); Assert.NotNull(ProjectTeamMemberRepository.Find(teamMember.Project(), teamMember.User())); var result = browser.Delete("/api/v1/project_team_member/delete", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); with.Query("project_guid", teamMember.Project().guid); with.Query("user_guid", teamMember.User().guid); }).Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); Assert.IsNull(ProjectTeamMemberRepository.Find(teamMember.Project(), teamMember.User())); }
public void SubmitWork_DataCorrect_WorkCreated() { var card = CardFaker.Create(); var project = card.Column().Board().Project(); var workType = project.WorkTypes()[0]; var result = new Browser(new DefaultNancyBootstrapper()) .Post("/api/v1/card/work/submit", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(UserFaker.Create().id)); with.Query("card_guid", card.guid); with.Query("work_type_guid", workType.guid); with.Query("proof", "some proof"); }).Result; Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); var json = JObject.Parse(result.Body.AsString()); Assert.AreEqual(card.guid, json["data"]["work_item"].Value <string>("card_guid")); }
public void Vote_WithActiveVote_VoteRewritten() { var user = UserFaker.Create(); var decision = EntityDecisionFaker.Create(user); var options = EntityDecisionOptionFaker.CreateMany(2, decision); EntityDecisionVoteFaker.Create(options[0], user); Assert.NotNull(options[0].UserVote(user)); var result = new Browser(new DefaultNancyBootstrapper()) .Post("/api/v1/entity/decision/vote", with => { with.HttpRequest(); with.Query("api_token", Jwt.FromUserId(user.id)); with.Query("option_guid", options[1].guid); }).Result; JObject.Parse(result.Body.AsString()); Assert.IsNull(options[0].UserVote(user)); Assert.NotNull(options[1].UserVote(user)); }
public void FromUserId_DataCorrect_AbleToGenerateToken() { var userId = new Random().Next(1, 99999); Jwt.FromUserId(userId); }
public JwtAuthController() { Get("/api/v1/login", _ => { var errors = ValidationProcessor.Process(Request, new IValidatorRule[] { new MinLength("email", 4), new MinLength("password", 4) }, true); if (errors.Count > 0) { return(HttpResponse.Errors(errors)); } var email = GetRequestStr("email").Replace(" ", ""); var password = GetRequestStr("password"); var user = UserRepository.FindByEmail(email); if (user == null) { return(HttpResponse.Error(HttpStatusCode.NotFound, "User not found")); } if (Encryptor.Encrypt(password) != user.password) { return(HttpResponse.Error( new HttpError(HttpStatusCode.Unauthorized, "Your email / password combination is incorrect") )); } if (!user.EmailConfirmed()) { return(HttpResponse.Error(HttpStatusCode.Forbidden, "You need to confirm your email")); } return(HttpResponse.Data(new JObject() { ["token"] = Jwt.FromUserId(user.id) })); }); Post("/api/v1/register", _ => { var errors = ValidationProcessor.Process(Request, new IValidatorRule[] { new ShouldHaveParameters(new[] { "login", "email", "password" }), new MinLength("login", 4), new MinLength("email", 4), new MinLength("password", 6), new ShouldBeValidEmail(), }, true); if (errors.Count > 0) { return(HttpResponse.Errors(errors)); } var login = GetRequestStr("login").Replace(" ", ""); var user = UserRepository.FindByLogin(login); if (user != null) { return(HttpResponse.Error( HttpStatusCode.Forbidden, "User with this login already exist" )); } var email = GetRequestStr("email").Replace(" ", ""); user = UserRepository.FindByEmail(email); if (user != null) { return(HttpResponse.Error( HttpStatusCode.Forbidden, "User with this login already exist" )); } var registeredUser = UserRepository.FindOrCreateByEmailAndLogin( email, login, GetRequestStr("password"), UserRepository.FindByGuid(GetRequestStr("referral_key")) ); var registerQueueItem = RegistrationQueueItemRepository.Create(registeredUser); MailGunSender.QueueTemplate( "confirm-your-email", registeredUser.email, "GitCom - you almost there!", new[] { new KeyValuePair <string, string>("confirmation_key", registerQueueItem.confirmation_key), } ); return(HttpResponse.Data(new JObject() { ["response"] = "Please confirm your email" })); }); Post("/api/v1/lazy_register", _ => { var errors = ValidationProcessor.Process(Request, new IValidatorRule[] { new ShouldHaveParameters(new[] { "email" }), new ShouldBeValidEmail(), }, true); if (errors.Count > 0) { return(HttpResponse.Errors(errors)); } var email = GetRequestStr("email").Replace(" ", "").ToLower(); var existingUser = UserRepository.FindByEmail(email); if (existingUser != null) { return(HttpResponse.Error( HttpStatusCode.Forbidden, "User with this email already exist, you need to log in" )); } var login = email.Split("@")[0]; var registeredUser = UserRepository.FindOrCreateByEmailAndLogin( email, login, Rand.RandomString() ); var registerQueueItem = RegistrationQueueItemRepository.Create(registeredUser); MailGunSender.QueueTemplate( "confirm-your-email", registeredUser.email, "GitCom - you almost there!", new[] { new KeyValuePair <string, string>("confirmation_key", registerQueueItem.confirmation_key), } ); return(HttpResponse.Data(new JObject() { ["token"] = Jwt.FromUserId(registeredUser.id) })); }); Post("/api/v1/register/confirm_email", _ => { var errors = ValidationProcessor.Process(Request, new IValidatorRule[] { new ShouldHaveParameters(new[] { "confirmation_key" }), }, true); if (errors.Count > 0) { return(HttpResponse.Errors(errors)); } var queuedItem = RegistrationQueueItemRepository.FindBy( "confirmation_key", GetRequestStr("confirmation_key") ); if (queuedItem == null) { return(HttpResponse.Error(HttpStatusCode.NotFound, "Confirmation key is invalid")); } if (queuedItem.email_confirmed) { return(HttpResponse.Error(HttpStatusCode.Forbidden, "Email is already confirmed")); } var me = UserRepository.Find(queuedItem.user_id); queuedItem.EmailConfirmed(); MailGunSender.QueueTemplate( "registration-complete", me.email, "GitCom - welcome!", new[] { new KeyValuePair <string, string>("login", me.login), } ); return(HttpResponse.Data(new JObject() { ["token"] = Jwt.FromUserId(me.id) })); }); }
public GithubAuthController() { var clientId = AppConfig.GetConfiguration("auth:external:github:client_id"); var clientSecret = AppConfig.GetConfiguration("auth:external:github:client_secret"); Get("/api/v1/auth/github/login_link/get", _ => { var loginLink = $"https://github.com/login/oauth/authorize?scope={Scopes}&client_id={clientId}"; return(HttpResponse.Data(new JObject() { ["login_link"] = loginLink })); }); Get("/api/v1/auth/github/get_auth_token", _ => { var responseBody = ""; var code = GetRequestStr("code"); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Accept", "application/json"); var response = client.PostAsync( "https://github.com/login/oauth/access_token", new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("client_id", clientId), new KeyValuePair <string, string>("client_secret", clientSecret), new KeyValuePair <string, string>("code", code), }) ).Result; if (response.IsSuccessStatusCode) { responseBody = response.Content.ReadAsStringAsync().Result; } } var json = JObject.Parse(responseBody); var accessToken = json.Value <string>("access_token"); if (accessToken == null) { return(HttpResponse.Error(HttpStatusCode.Unauthorized, "We're unable to get your access token, please try again")); } var githubClient = new GitHubClient(new ProductHeaderValue("GitCom")); githubClient.Credentials = new Credentials(accessToken); var githubUser = githubClient.User.Current().Result; var userEmail = githubUser.Email ?? $"{Rand.RandomString()}[email protected]"; var user = UserRepository.FindByEmail(userEmail) ?? UserRepository.FindOrCreateByEmailAndLogin( userEmail, githubUser.Login, null, UserRepository.FindByGuid(GetRequestStr("referral_key")) ); var tokenModel = ServiceAccessTokenRepository.FindOrUpdateAccessToken(user, accessToken, ServiceType.GitHub); tokenModel.UpdateCol("origin_user_id", githubUser.Id.ToString()); return(HttpResponse.Data(new JObject() { ["token"] = Jwt.FromUserId(user.id) })); }); }