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

Prevent avatar 404 console errors #742

Merged
merged 17 commits into from
Oct 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Backend.Tests/Mocks/UserServiceMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,5 +105,11 @@ public Task<ResultOfUpdate> ChangePassword(string userId, string password)
{
return Task.FromResult(ResultOfUpdate.Updated); //TODO: more sophisticated mock
}
public void Sanitize(User user)
{
user.Avatar = null;
user.Password = null;
user.Token = null;
}
}
}
1 change: 1 addition & 0 deletions Backend/Controllers/AvatarController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ public async Task<IActionResult> UploadAvatar(string userId, [FromForm] FileUplo

// Update the user's avatar file
gotUser.Avatar = fileUpload.FilePath;
gotUser.HasAvatar = true;
_ = await _userService.Update(userId, gotUser);

return new OkResult();
Expand Down
1 change: 1 addition & 0 deletions Backend/Interfaces/IUserService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,6 @@ public interface IUserService
Task<User> Authenticate(string username, string password);
Task<User> MakeJwt(User user);
Task<ResultOfUpdate> ChangePassword(string userId, string password);
void Sanitize(User user);
}
}
7 changes: 7 additions & 0 deletions Backend/Models/User.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ public class User
[BsonElement("avatar")]
public string Avatar { get; set; }

[BsonElement("hasAvatar")]
public bool HasAvatar { get; set; }

[BsonElement("name")]
public string Name { get; set; }

Expand Down Expand Up @@ -62,6 +65,7 @@ public User()
{
Id = "";
Avatar = "";
HasAvatar = false;
Name = "";
Email = "";
Phone = "";
Expand All @@ -82,6 +86,7 @@ public User Clone()
{
Id = Id.Clone() as string,
Avatar = Avatar.Clone() as string,
HasAvatar = HasAvatar,
Name = Name.Clone() as string,
Email = Email.Clone() as string,
Phone = Phone.Clone() as string,
Expand Down Expand Up @@ -113,6 +118,7 @@ public bool ContentEquals(User other)
return
other.Id.Equals(Id) &&
other.Avatar.Equals(Avatar) &&
other.HasAvatar.Equals(HasAvatar) &&
other.Name.Equals(Name) &&
other.Email.Equals(Email) &&
other.Phone.Equals(Phone) &&
Expand Down Expand Up @@ -145,6 +151,7 @@ public override int GetHashCode()
var hash = new HashCode();
hash.Add(Id);
hash.Add(Avatar);
hash.Add(HasAvatar);
hash.Add(Name);
hash.Add(Email);
hash.Add(Phone);
Expand Down
35 changes: 20 additions & 15 deletions Backend/Services/UserApiServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,25 +157,26 @@ public async Task<User> MakeJwt(User user)
new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);

// Sanitize user to remove password, avatar path, and old token
// Then add updated token.
Sanitize(user);
user.Token = tokenHandler.WriteToken(token);

if (await Update(user.Id, user) != ResultOfUpdate.Updated)
{
return null;
}

// Remove password and avatar filepath before returning
user.Password = "";
user.Avatar = "";

return user;
}

/// <summary> Finds all <see cref="User"/>s </summary>
public async Task<List<User>> GetAllUsers()
{
var users = await _userDatabase.Users.Find(_ => true).ToListAsync();
return users.Select(c => { c.Avatar = ""; c.Password = ""; c.Token = ""; return c; }).ToList();
users.ForEach(Sanitize);
return (users);
}

/// <summary> Removes all <see cref="User"/>s </summary>
Expand All @@ -193,11 +194,8 @@ public async Task<User> GetUser(string userId)
var filter = filterDef.Eq(x => x.Id, userId);

var userList = await _userDatabase.Users.FindAsync(filter);

var user = userList.FirstOrDefault();
user.Avatar = "";
user.Password = "";
user.Token = "";
Sanitize(user);
return user;
}

Expand Down Expand Up @@ -256,11 +254,7 @@ public async Task<User> Create(User user)
// Replace password with encoded, hashed password.
user.Password = Convert.ToBase64String(hash);
await _userDatabase.Users.InsertOneAsync(user);

// Important, don't send plaintext password back to user.
user.Password = "";
user.Avatar = "";

Sanitize(user);
return user;
}

Expand All @@ -272,6 +266,15 @@ public async Task<bool> Delete(string userId)
return deleted.DeletedCount > 0;
}

/// <summary> Removes avatar path, password, and token from <see cref="User"/> </summary>
public void Sanitize(User user)
{
// .Avatar or .Token set to "" or null will not be updated in the database
user.Avatar = null;
user.Password = null;
user.Token = null;
}

/// <summary> Updates <see cref="User"/> with specified userId </summary>
/// <returns> A <see cref="ResultOfUpdate"/> enum: success of operation </returns>
public async Task<ResultOfUpdate> Update(string userId, User user, bool updateIsAdmin = false)
Expand All @@ -280,6 +283,7 @@ public async Task<ResultOfUpdate> Update(string userId, User user, bool updateIs

// Note: Nulls out values not in update body
var updateDef = Builders<User>.Update
.Set(x => x.HasAvatar, user.HasAvatar)
.Set(x => x.Name, user.Name)
.Set(x => x.Email, user.Email)
.Set(x => x.Phone, user.Phone)
Expand All @@ -290,11 +294,12 @@ public async Task<ResultOfUpdate> Update(string userId, User user, bool updateIs
.Set(x => x.Username, user.Username)
.Set(x => x.UILang, user.UILang);

// If .Avatar or .Token has been set to null or "",
// this prevents it from being erased in the database
if (!string.IsNullOrEmpty(user.Avatar))
{
updateDef = updateDef.Set(x => x.Avatar, user.Avatar);
}

if (!string.IsNullOrEmpty(user.Token))
{
updateDef = updateDef.Set(x => x.Token, user.Token);
Expand Down
19 changes: 9 additions & 10 deletions src/components/ProjectSettings/ProjectUsers/ActiveUsers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,18 @@ export default class ActiveUsers extends React.Component<UserProps, UserState> {

private populateUsers() {
getAllUsersInCurrentProject()
.then((projUsers) => {
.then(async (projUsers) => {
this.setState({ projUsers });
projUsers.forEach((u: User) => {
avatarSrc(u.id)
.then((result) => {
let userAvatar = this.state.userAvatar;
userAvatar[u.id] = result;
this.setState({ userAvatar });
})
.catch((err) => console.log(err));
const userAvatar = this.state.userAvatar;
const promises = projUsers.map(async (u) => {
if (u.hasAvatar) {
userAvatar[u.id] = await avatarSrc(u.id);
}
});
await Promise.all(promises);
this.setState({ userAvatar });
})
.catch((err) => console.log(err));
.catch((err) => console.error(err));
}

render() {
Expand Down
22 changes: 10 additions & 12 deletions src/components/ProjectSettings/ProjectUsers/ProjectUsers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,26 +73,24 @@ class ProjectUsers extends React.Component<UserProps, UserState> {
this.setState({ projUsers });
backend
.getAllUsers()
.then((returnedUsers) => {
.then(async (returnedUsers) => {
this.setState((prevState) => ({
allUsers: returnedUsers.filter(
(user) => !prevState.projUsers.find((u) => u.id === user.id)
),
}));
returnedUsers.forEach((u: User) => {
backend
.avatarSrc(u.id)
.then((result) => {
let userAvatar = this.state.userAvatar;
userAvatar[u.id] = result;
this.setState({ userAvatar });
})
.catch((err) => console.log(err));
const userAvatar = this.state.userAvatar;
const promises = projUsers.map(async (u) => {
if (u.hasAvatar) {
userAvatar[u.id] = await backend.avatarSrc(u.id);
}
});
await Promise.all(promises);
this.setState({ userAvatar });
})
.catch((err) => console.log(err));
.catch((err) => console.error(err));
})
.catch((err) => console.log(err));
.catch((err) => console.error(err));
}

addToProject(user: User) {
Expand Down
47 changes: 17 additions & 30 deletions src/types/user.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,22 @@
import { Hash } from "../goals/MergeDupGoal/MergeDupStep/MergeDupsTree";

export class User {
id: string;
avatar: string;
name: string;
email: string;
phone: string;
otherConnectionField: string;
projectRoles: Hash<string>;
workedProjects: Hash<string>;
agreement: boolean;
password: string;
username: string;
uiLang: string;
token: string;
isAdmin: boolean;
id: string = "";
avatar: string = "";
hasAvatar: boolean = false;
email: string = "";
phone: string = "";
otherConnectionField: string = "";
projectRoles: Hash<string> = {};
workedProjects: Hash<string> = {};
agreement: boolean = false;
uiLang: string = "";
token: string = "";
isAdmin: boolean = false;

constructor(name: string, username: string, password: string) {
this.id = "";
this.avatar = "";
this.name = name;
this.email = "";
this.phone = "";
this.otherConnectionField = "";
this.projectRoles = {};
this.workedProjects = {};
this.agreement = false;
this.password = password;
this.username = username;
this.uiLang = "";
this.token = "";
this.isAdmin = false;
}
constructor(
public name: string,
public username: string,
public password: string
) {}
}