Exemplo n.º 1
0
        public async Task <GenericResponseDTO <int> > UpdateUserProfile(ProfileUpdateDTO profileUpdateInfo)
        {
            int currentUserID;

            try {
                currentUserID = authHelper.GetCurrentUserId(User);
            } catch (System.NullReferenceException) {
                return(new GenericResponseDTO <int> {
                    Message = "Not logged in.",
                    Success = false
                });
            }

            User currentUser = await database.Users
                               .AsQueryable()
                               .FirstOrDefaultAsync(user => user.Id == currentUserID);

            currentUser.FirstName = profileUpdateInfo.FirstName;
            currentUser.LastName  = profileUpdateInfo.LastName;
            await database.SaveChangesAsync();

            return(new GenericResponseDTO <int>
            {
                Success = true,
                Data = currentUser.Id
            });
        }
Exemplo n.º 2
0
        public async Task Login()
        {
            var currentUser = Context.User;

            // Check to make sure the user is not already linked
            var alreadyLinkedUser = await database.Users
                                    .AsQueryable()
                                    .Where(x => x.DiscordId == currentUser.Id.ToString())
                                    .FirstOrDefaultAsync();

            if (alreadyLinkedUser != null)
            {
                await ReplyAsync(
                    $@"{currentUser.Mention} your account is already linked with the email, {alreadyLinkedUser.Email}." +
                    "If you would like to unlink you account you can use the `!unlink` command."
                    );

                return;
            }

            var linkKey   = Guid.NewGuid().ToString().Replace("-", "") + Guid.NewGuid().ToString().Replace("-", "");
            var discordId = currentUser.Id;

            var discordLink = new DiscordLink()
            {
                DiscordId = discordId.ToString(),
                LinkKey   = linkKey
            };

            database.Add(discordLink);
            await database.SaveChangesAsync();

            await ReplyAsync($"{currentUser.Mention} a direct message has been sent with further instructions for setting up your account.");

            await currentUser.SendMessageAsync(
                "Please login to your NTime account using the following link to link your discord account to your NTime account " +
                configuration["WebsiteLink"] + "auth/login?discordLink=" + linkKey
                );
        }
Exemplo n.º 3
0
        public async Task <GenericResponseDTO <TimerDTO> > StartTimer(TimerCreateDTO timerInfo)
        {
            User currentUser = await authHelper.GetCurrentUser(User, database);

            Project project = await database.Projects
                              .AsQueryable()
                              .FirstOrDefaultAsync(
                p => p.Id == timerInfo.ProjectId &&
                (p.Students.Any(s => s.Id == currentUser.Id) || p.Teacher.Id == currentUser.Id));

            if (project == null)
            {
                return(new GenericResponseDTO <TimerDTO> {
                    Message = "Could not find project.",
                    Success = false
                });
            }

            Timer timer = (await database.Timers
                           .AddAsync(new Timer {
                User = await authHelper.GetCurrentUser(User, database),
                StartTime = DateTime.UtcNow,
                Notes = timerInfo.Notes,
                Project = project
            })).Entity;

            await database.SaveChangesAsync();

            return(new GenericResponseDTO <TimerDTO> {
                Data = new TimerDTO {
                    Id = timer.Id,
                    StartTime = timer.StartTime,
                    Notes = timer.Notes,
                    ProjectId = timer.Project.Id
                },
                Success = true
            });
        }
Exemplo n.º 4
0
        public async Task <GenericResponseDTO <int> > CreateTime(TimeEntryDTO data)
        {
            var results = new GenericResponseDTO <int>()
            {
                Success = true
            };

            var newTimeEntry = new TimeEntry()
            {
                CreatedTime  = DateTime.UtcNow,
                Day          = data.Day,
                LastModified = DateTime.UtcNow,
                Length       = data.Length,
                Notes        = data.Notes,
                Project      = await database.Projects.AsQueryable().SingleAsync(x => x.Id == data.ProjectId),
                User         = await authHelper.GetCurrentUser(User, database)
            };

            database.TimeEntries.Add(newTimeEntry);
            await database.SaveChangesAsync();

            results.Data = newTimeEntry.Id;
            return(results);
        }
Exemplo n.º 5
0
        public async Task <GenericResponseDTO <bool> > SetTags(List <CreateTagDTO> tags)
        {
            var currentUserId = authHelper.GetCurrentUserId(User);

            // Only allow the teacher to tag a project
            var project = await database.Projects
                          .Include(x => x.Tags)
                          .FirstAsync(x => x.Id == tags.First().ProjectId&& x.Teacher.Id == currentUserId && x.ArchivedDate == null);

            if (project == null)
            {
                return(new GenericResponseDTO <bool>()
                {
                    Message = "Couldn't find the project",
                    Success = false
                });
            }

            project.Tags = new List <Tag>();

            foreach (var newTag in tags)
            {
                var tag = new Tag()
                {
                    Name    = newTag.Tag,
                    Project = project
                };

                project.Tags.Add(tag);
            }

            await database.SaveChangesAsync();

            return(new GenericResponseDTO <bool>()
            {
                Data = true,
                Success = true
            });
        }
Exemplo n.º 6
0
        public async Task Stop()
        {
            User user = database.Users
                        .AsQueryable()
                        .FirstOrDefault(u => u.DiscordId == Context.User.Id.ToString());

            if (user == null)
            {
                await Context.Message.ReplyAsync("Your Discord account is not currently linked to an NTime account. Use `!login` to link your accounts together.");

                return;
            }

            List <Timer> timers = database.Timers
                                  .AsQueryable()
                                  .Where(timer => timer.User.Id == user.Id)
                                  .ToList();

            if (timers.Count == 0)
            {
                await Context.Message.ReplyAsync("There are no active timers to stop.");

                return;
            }
            else if (timers.Count == 1)
            {
                DateTime timeEntryCreationTime = DateTime.UtcNow;

                TimeEntry timeEntry = new TimeEntry {
                    CreatedTime  = timeEntryCreationTime,
                    Notes        = timers[0].Notes,
                    Project      = timers[0].Project,
                    LastModified = timeEntryCreationTime,
                    User         = user,
                    Length       = Math.Round((timeEntryCreationTime - timers[0].StartTime).TotalHours, 2),
                    Day          = timeEntryCreationTime
                };

                database.TimeEntries.Add(timeEntry);

                database.Timers.Remove(timers[0]);

                await database.SaveChangesAsync();

                await Context.Message.ReplyAsync("Timer stopped for the project **" + timers[0].Project.Name + "**, and a new time entry with " + timeEntry.Length + " hours on it has been added.");

                return;
            }

            timers.Sort((a, b) => a.Project.Name.CompareTo(b.Project.Name));

            EmbedBuilder embedBuilder = new EmbedBuilder()
            {
                Color       = new Color(35, 45, 154),
                Title       = "Active Timers",
                Description = "Multiple projects with active timers were found, please select one to stop:"
            };

            for (int i = 0; i < timers.Count; i++)
            {
                embedBuilder.AddField(field => {
                    field.Name     = timers[i].Project.Name + " (Active for " + Math.Round((DateTime.UtcNow - timers[i].StartTime).TotalHours, 2) + " hours)";
                    field.Value    = "!stop " + (i + 1);
                    field.IsInline = false;
                });
            }

            embedBuilder.WithFooter(footer => {
                footer.Text    = "(you can also stop a timer directly using !stop [project name])";
                footer.IconUrl = "";
            });

            await Context.Message.ReplyAsync("", false, embedBuilder.Build());

            return;
        }
Exemplo n.º 7
0
        public async Task <GenericResponseDTO <AccessKeysDTO> > Login(UserDTO loginData)
        {
            try
            {
                // Get user with a matching username and password hash
                var    hashedPassword = authHelper.GetPasswordHash(loginData.Password, configuration);
                String message        = "";
                var    curUser        = await database.Users
                                        .Include(x => x.Projects)
                                        .FirstOrDefaultAsync(u => u.Email.ToLower() == loginData.Email.ToLower() && u.Password.SequenceEqual(hashedPassword));

                // If there was not a matching user then return an error
                if (curUser == null)
                {
                    return(new GenericResponseDTO <AccessKeysDTO>()
                    {
                        Success = false,
                        Message = "Invalid username or password"
                    });
                }

                // Generate the JWT and Refresh tokens and save the refresh token to the db
                var accessToken  = authHelper.GenerateJSONWebToken(curUser, configuration);
                var refreshToken = authHelper.GenerateRefreshToken();

                var userRefreshToken = new RefreshToken()
                {
                    Token = refreshToken,
                    User  = curUser
                };

                // check if the user logged in with an invite code, if they did, add them to a project
                if (!String.IsNullOrWhiteSpace(loginData.InviteCode))
                {
                    Project project = await database.Projects
                                      .AsQueryable()
                                      .FirstOrDefaultAsync(p => p.InviteCode == loginData.InviteCode);

                    if (project != null)
                    {
                        if (project.ArchivedDate != null)
                        {
                            message = "Unable to add to Archived Project";
                        }
                        else
                        {
                            if (curUser.Projects.Contains(project))
                            {
                                message = "User already in project";
                            }
                            else
                            {
                                if (project.Teacher == curUser)
                                {
                                    message = "User already in project";
                                }
                                else
                                {
                                    curUser.Projects.Add(project);
                                    message = "Added User to Project";
                                }
                            }
                        }
                    }
                    else
                    {
                        message = "Project not found";
                    }
                }

                await database.AddAsync(userRefreshToken);

                await database.SaveChangesAsync();

                return(new GenericResponseDTO <AccessKeysDTO>()
                {
                    Success = true,
                    Data = new AccessKeysDTO()
                    {
                        AccessToken = accessToken,
                        RefreshToken = refreshToken
                    },
                    Message = message
                });
            }
            catch
            {
                return(new GenericResponseDTO <AccessKeysDTO>()
                {
                    Success = false,
                    Message = "An unknown error has occurred"
                });
            }
        }