Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[GoalsActions] Fix user updating during project creation #693

Merged
merged 13 commits into from
Sep 8, 2020
11 changes: 8 additions & 3 deletions Backend.Tests/Controllers/UserEditControllerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public class UserEditControllerTests
private string _projId;
private IPermissionService _permissionService;
private IUserService _userService;
private User _jwtAuthenticatedUser;

[SetUp]
public void Setup()
Expand All @@ -36,7 +37,11 @@ public void Setup()
{
ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }
};

_jwtAuthenticatedUser = new User { Username = "user", Password = "pass" };
_userService.Create(_jwtAuthenticatedUser);
_jwtAuthenticatedUser = _userService.Authenticate(
_jwtAuthenticatedUser.Username, _jwtAuthenticatedUser.Password).Result;
_userEditController.ControllerContext.HttpContext.Request.Headers["UserId"] = _jwtAuthenticatedUser.Id;
}

private UserEdit RandomUserEdit()
Expand Down Expand Up @@ -89,8 +94,8 @@ public void TestGetUserEdit()
public void TestCreateUserEdit()
{
var userEdit = new UserEdit { ProjectId = _projId };
var id = (_userEditController.Post(_projId).Result as ObjectResult).Value as string;
userEdit.Id = id;
var withUser = (_userEditController.Post(_projId).Result as ObjectResult).Value as WithUser;
userEdit.Id = withUser.UpdatedUser.WorkedProjects[_projId];
Assert.Contains(userEdit, _userEditRepo.GetAllUserEdits(_projId).Result);
}

Expand Down
16 changes: 14 additions & 2 deletions Backend/Controllers/UserEditController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public async Task<IActionResult> Get(string projectId, string userEditId)

/// <summary> Creates a <see cref="UserEdit"/> </summary>
/// <remarks> POST: v1/projects/{projectId}/useredits </remarks>
/// <returns> Id of create UserEdit </returns>
/// <returns> UpdatedUser </returns>
[HttpPost]
public async Task<IActionResult> Post(string projectId)
{
Expand All @@ -114,9 +114,21 @@ public async Task<IActionResult> Post(string projectId)
return new ForbidResult();
}

// Generate the new userEdit
var userEdit = new UserEdit { ProjectId = projectId };
await _repo.Create(userEdit);
return new OkObjectResult(userEdit.Id);
// Update current user
var currentUserId = _permissionService.GetUserId(HttpContext);
var currentUser = await _userService.GetUser(currentUserId);
currentUser.WorkedProjects.Add(projectId, userEdit.Id);
await _userService.Update(currentUserId, currentUser);
// Generate the JWT based on the new userEdit
currentUser = await _userService.MakeJwt(currentUser);
await _userService.Update(currentUserId, currentUser);

var output = new WithUser() { UpdatedUser = currentUser };

return new OkObjectResult(output);
}

/// <summary> Adds a goal to <see cref="UserEdit"/> with specified id </summary>
Expand Down
8 changes: 8 additions & 0 deletions Backend/Models/User.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,4 +166,12 @@ public class Credentials
public string Username { get; set; }
public string Password { get; set; }
}

/// <summary> Contains UpdatedUser for Axios interceptor. </summary>
public class WithUser
{
public User UpdatedUser;

public WithUser() { }
}
}
8 changes: 4 additions & 4 deletions src/backend/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ const backendServer = axios.create({

backendServer.interceptors.response.use(
(resp) => {
if (resp.data.__UpdatedUser) {
LocalStorage.setCurrentUser(resp.data.__UpdatedUser);
if (resp.data.updatedUser) {
LocalStorage.setCurrentUser(resp.data.updatedUser);
}
delete resp.data.__UpdatedUser;
delete resp.data.updatedUser;
return resp;
},
(err) => {
Expand Down Expand Up @@ -458,7 +458,7 @@ function goalNameToGoalTypeId(goalName: string): string {
return goalType.toString();
}

export async function createUserEdit(): Promise<string> {
export async function createUserEdit(): Promise<Object> {
let resp = await backendServer.post(
`projects/${LocalStorage.getProjectId()}/useredits`,
"",
Expand Down
38 changes: 3 additions & 35 deletions src/components/GoalTimeline/GoalsActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,30 +66,17 @@ export function asyncLoadExistingUserEdits(
};
}

function asyncCreateNewUserEditsObject(projectId: string) {
return async () => {
await Backend.createUserEdit()
.then(async (userEditId: string) => {
let updatedUser: User = updateUserIfExists(projectId, userEditId);
await Backend.updateUser(updatedUser);
})
.catch((err) => {
console.log(err);
});
};
}

export function asyncGetUserEdits() {
return async (dispatch: ThunkDispatch<StoreState, any, GoalAction>) => {
const user: User | null = LocalStorage.getCurrentUser();
if (user) {
const projectId: string = LocalStorage.getProjectId();
const projectId: string = LocalStorage.getProjectId();
if (user && projectId) {
const userEditId: string | undefined = getUserEditId(user);

if (userEditId !== undefined) {
dispatch(asyncLoadExistingUserEdits(projectId, userEditId));
} else {
dispatch(asyncCreateNewUserEditsObject(projectId));
dispatch(Backend.createUserEdit);
}
}
};
Expand Down Expand Up @@ -200,25 +187,6 @@ export function getUserEditId(user: User): string | undefined {
}
}

function updateUserIfExists(projectId: string, userEditId: string): User {
let currentUser: User | null = LocalStorage.getCurrentUser();
let updatedUser: User = new User("", "", "");
if (currentUser) {
updatedUser = updateUserWithUserEditId(currentUser, projectId, userEditId);
LocalStorage.setCurrentUser(updatedUser);
}
return updatedUser;
}

function updateUserWithUserEditId(
user: User,
projectId: string,
userEditId: string
): User {
user.workedProjects[projectId] = userEditId;
return user;
}

export function getIndexInHistory(history: Goal[], currentGoal: Goal): number {
for (let i = 0; i < history.length; i++) {
if (history[i].hash === currentGoal.hash) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ jest.mock("../../../backend", () => {
return Promise.resolve(mockUserEdit);
}),
createUserEdit: jest.fn(() => {
return Promise.resolve(mockUserEditId);
return Promise.resolve({});
}),
updateUser: jest.fn((_user: User) => {
return Promise.resolve(mockUser);
Expand Down