Beispiel #1
0
        // POST api/<controller>
        public HttpResponseMessage Post([FromBody] int userId)
        {
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(Request.Headers);

            if (securityContext == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            DatabaseContext db = new DatabaseContext();
            SessionManager  sm = new SessionManager();

            // TODO modify this to allow admins to use this.
            if (securityContext.UserId != userId)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            try
            {
                sm.InvalidateSession(securityContext.Token);
                //

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch
            {
                return(Request.CreateResponse(HttpStatusCode.ExpectationFailed));
            }
        }
        public IHttpActionResult DeleteConversation(int conversationId)
        {
            //The authentication part start from here
            //Create security context from the token

            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());
            }
            //Validate the token
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());
            }

            //Create authorization manager from security context to check claims
            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );

            List <string> requiredClaims = new List <string>()
            {
                "CanSendMessage"
            };

            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());
            }
            else
            {
                UserManager um = new UserManager();
                //Find auth user Id from auth username
                _authUserId = um.FindByUserName(securityContext.UserName).Id;

                try
                {
                    //string updatedToken = sm.RefreshSession(securityContext.Token);

                    //Delete conversation using conversationId
                    var conversation = _messengerManager.DeleteConversation(conversationId);
                    return(Ok(new { conversation = conversation } /*new { SITtoken = updatedToken}*/));
                }

                catch (DbUpdateException ex)
                {
                    return(Content(HttpStatusCode.NotFound, "conversation does not exist to be delete"));
                }
            }
        }
        public IHttpActionResult DeleteFriend(int friendId)
        {
            //The authentication part start from here
            //Create security context from the token
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());
            }
            SessionManager sm = new SessionManager();


            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());
            }

            //Create authorization manager from security context to check claims
            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );


            List <string> requiredClaims = new List <string>()
            {
                "CanSendMessage"
            };

            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());
            }
            else
            {
                UserManager um = new UserManager();

                // Get authUserId from auth username
                _authUserId = um.FindByUserName(securityContext.UserName).Id;
                try
                {
                    //string updatedToken = sm.RefreshSession(securityContext.Token);

                    // Try to remove a user from the friendlist
                    _messengerManager.RemoveUserFromFriendList(_authUserId, friendId);
                    return(Ok(/*new { SITtoken = updatedToken }*/));
                }
                catch (DbUpdateException ex)
                {
                    return(Content(HttpStatusCode.InternalServerError, "There is a error removing user from friend list" /*SITtoken = updatedToken*/));
                }
            }
        }
Beispiel #4
0
        public IHttpActionResult Search([FromUri] SearchRequest request)
        {
            if (!ModelState.IsValid || request is null)
            {
                // 412 Response
                return(Content(HttpStatusCode.PreconditionFailed, new SearchResponse(Constants.InvalidRequest)));
            }

            // Validate token and session
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                _loggingManager.LogError(securityContext.UserName, HttpContext.Current.Request.ToString(), Constants.InvalidSecurityContext);
                return(Content(HttpStatusCode.Unauthorized, Constants.InvalidSecurityContext));
            }
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                _loggingManager.LogError(securityContext.UserName, HttpContext.Current.Request.ToString(), Constants.InvalidSession);
                return(Content(HttpStatusCode.Unauthorized, Constants.InvalidSession));
            }

            // Update token
            string updatedToken = sm.RefreshSession(securityContext.Token);

            try
            {
                using (var _db = new DatabaseContext())
                {
                    ISearchManager manager = new SearchManager(_db);

                    // Search
                    var results = new SearchResponse(manager.Search(request), updatedToken);
                    return(Content(HttpStatusCode.OK, results));
                }
            }
            catch (Exception x) when(x is ArgumentException)
            {
                _loggingManager.LogError(securityContext.UserName, HttpContext.Current.Request.ToString(), x.Message);
                return(Content(HttpStatusCode.BadRequest, new SearchResponse(x.Message)));
            }
            catch (Exception x)
            {
                _loggingManager.LogError(securityContext.UserName, HttpContext.Current.Request.ToString(), x.Message);
                return(Content(HttpStatusCode.InternalServerError, new SearchResponse(x.Message)));
            }
        }
Beispiel #5
0
        public HttpResponseMessage GetUserInfoWithId(int id)
        {
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );
            // TODO get this from table in database.
            List <string> requiredClaims = new List <string>()
            {
                "CanReadOwnStudentAccount"
            };

            if (securityContext.UserId != id ||
                !authorizationManager.CheckClaims(requiredClaims))
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            else
            {
                UserManager um      = new UserManager();
                UserDTO     userDTO = um.GetUserInfo(id);
                var         student = um.FindStudentById(id);
                if (student is null)
                {
                    userDTO.SchoolId = 0;
                }
                else
                {
                    userDTO.SchoolId = student.SchoolDepartment.SchoolId;
                }
                string updatedToken = sm.RefreshSession(securityContext.Token);
                return(Request.CreateResponse(
                           HttpStatusCode.OK, new { User = userDTO, SITtoken = updatedToken }
                           ));
            }
        }
Beispiel #6
0
        public IHttpActionResult GetUserProfile([FromUri] int accountId)
        {
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());
            }
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());
            }

            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );
            // TODO get this from table in database.
            List <string> requiredClaims = new List <string>()
            {
                "CanReadAStudentPublicInformation"
            };

            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());
            }
            else
            {
                try
                {
                    UserManager userManager  = new UserManager();
                    string      updatedToken = sm.RefreshSession(securityContext.Token);
                    var         results      = userManager.GetUserProfile(accountId);
                    return(Ok(new { User = results, SITtoken = updatedToken }));
                }
                catch (Exception x) when(x is ArgumentException)
                {
                    return(Content(HttpStatusCode.BadRequest, x.Message));
                }
                catch (Exception x)
                {
                    return(Content(HttpStatusCode.InternalServerError, x.Message));
                }
            }
        }
Beispiel #7
0
        public IHttpActionResult EditUserInfo(UserProfileDTO newProfileInfo)
        {
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());
            }
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());
            }
            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );

            List <string> requiredClaims = new List <string>()
            {
                "CanEditOwnAccount"
            };
            UserManager um = new UserManager();

            try
            {
                um.EditStudentProfile(securityContext.UserId, newProfileInfo);
                string updatedToken = sm.RefreshSession(securityContext.Token);
                return(Ok(updatedToken));
            }
            catch (Exception ex) when(ex is AccountNotFoundException)
            {
                return(BadRequest("Account not found"));
            }
            catch (Exception ex) when(ex is NotAStudentException)
            {
                return(BadRequest("Can't modify a non student account."));
            }
            catch (Exception ex) when(ex is DepartmentNotFoundException)
            {
                return(BadRequest("Department doesn't exist."));
            }
            catch (Exception ex)
            {
                return(InternalServerError());
            }
        }
Beispiel #8
0
        public IHttpActionResult GetPublicUserInfoWithId(int id)
        {
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());
            }
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());
            }

            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );
            // TODO get this from table in database.
            List <string> requiredClaims = new List <string>()
            {
                "CanReadAStudentPublicInformation"
            };

            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());
            }
            else
            {
                UserManager um             = new UserManager();
                UserDTO     userDTO        = um.GetUserInfo(id);
                var         publicUserInfo = new
                {
                    Id        = userDTO.Id,
                    UserName  = userDTO.UserName,
                    FirstName = userDTO.FirstName,
                    LastName  = userDTO.LastName,
                    Exp       = userDTO.Exp
                };
                string updatedToken = sm.RefreshSession(securityContext.Token);
                return(Ok(
                           new { User = publicUserInfo, SITtoken = updatedToken }
                           ));
            }
        }
        public IHttpActionResult GetUserIdWithUsername(string username)
        {
            UserManager umManager = new UserManager();
            //The authentication part start from here
            //Create security context from the token
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());
            }
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());;
            }

            //Create authorization manager from security context to check claims
            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );

            List <string> requiredClaims = new List <string>()
            {
                "CanSendMessage"
            };

            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());;
            }
            else
            {
                var user = umManager.FindByUserName(username);
                if (user != null)
                {
                    return(Ok(user.Id));
                }
                else
                {
                    return(NotFound());
                }
            }
        }
        public IHttpActionResult GetAuthUserIdAndUsername()
        {
            //The authentication part start from here
            //Create security context from the token
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());
            }
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());;
            }

            //Create authorization manager from security context to check claims
            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );

            List <string> requiredClaims = new List <string>()
            {
                "CanSendMessage"
            };

            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());;
            }
            else
            {
                UserManager um   = new UserManager();
                Account     user = um.FindByUserName(securityContext.UserName);
                _authUserId = user.Id;
                var authUsername = user.UserName;
                //string updatedToken = sm.RefreshSession(securityContext.Token);

                return(Ok(new { authUserId = _authUserId, authUsername = authUsername /*SITtoken = updatedToken*/ }));
            }
        }
Beispiel #11
0
        public int AuthorizeUser(List <string> requiredClaims)
        {
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(0);
            }
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(0);
            }

            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );
            // TODO get this from table in database.
            //List<string> requiredClaims = new List<string>()
            //{
            //    "CanPostQuestion"
            //};
            //if (!authorizationManager.CheckClaims(requiredClaims))
            //{
            //    return 0;
            //}
            //else
            //{
            UserManager um   = new UserManager();
            Account     user = um.FindByUserName(securityContext.UserName);

            if (user == null)
            {
                return(0);
            }
            authUserId = um.FindByUserName(securityContext.UserName).Id;
            //}
            return(authUserId);
        }
Beispiel #12
0
        public HttpResponseMessage GetContextId()
        {
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
            string updatedToken = sm.RefreshSession(securityContext.Token);

            // TODO finish this.
            return(Request.CreateResponse(
                       HttpStatusCode.OK, new { userid = securityContext.UserId, SITtoken = updatedToken }
                       ));
        }
        public IHttpActionResult GetMessageInConversation(int conversationId)
        {
            //The authentication part start from here
            //Create security context from the token
            UserManager     um = new UserManager();
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());
            }

            //Validate the token
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());
            }

            //Create authorization manager from security context to check claims
            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );

            List <string> requiredClaims = new List <string>()
            {
                "CanSendMessage"
            };

            //Create authorization manager from security context to check claims
            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());
            }
            else
            {
                var authUsername = securityContext.UserName;


                // Get conversation from conversation Id
                var conversation = _messengerManager.GetConversationFromId(conversationId);

                // Get contact username in the conversation
                var contactUsername = _messengerManager.GetContactUsernameFromConversation(conversationId);

                //Temporary username used to decide which username to display in the message
                var temPUsername = "";

                //Get all messages in the conversation
                var messageList = _messengerManager.GetMessageInConversation(conversationId);
                if (messageList != null)
                {
                    // Create list of messageDTO for transfer
                    List <StoredMessageDTO> messageDTOList = new List <StoredMessageDTO>();
                    foreach (Message m in messageList)
                    {
                        // If true the message is come from the authenticated user
                        if (m.OutgoingMessage == true)
                        {
                            // Set temporary username to auth username
                            temPUsername = securityContext.UserName;
                        }
                        else
                        {
                            //Otherwise, set the temp username to contactname
                            temPUsername = contactUsername;
                        }

                        //Add StoreMessageDTO to messageDTO List
                        //Stored Message DTO is sent from back end
                        // is used to differenate between the MessageDTO sent from the front end
                        messageDTOList.Add(new StoredMessageDTO
                        {
                            Id              = m.Id,
                            SenderUsername  = temPUsername,
                            MessageContent  = m.MessageContent,
                            OutgoingMessage = m.OutgoingMessage,
                            CreatedDate     = m.CreatedDate
                        });
                    }
                    return(Ok(new { messages = messageDTOList, contactUsername = contactUsername /*SITtoken = updatedToken*/ }));
                }

                return(Content(HttpStatusCode.NotFound, "No message in conversation"));
            }
        }
        public IHttpActionResult GetFriendList()
        {
            //The authentication part start from here
            //Create security context from the token
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());;
            }

            //Validate the token
            SessionManager sm = new SessionManager();


            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());;
            }

            //Create authorization manager from security context to check claims
            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );
            // TODO get this from table in database.
            List <string> requiredClaims = new List <string>()
            {
                "CanSendMessage"
            };

            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());;
            }
            else
            {
                UserManager um = new UserManager();

                // Get authUserId from auth username
                _authUserId = um.FindByUserName(securityContext.UserName).Id;

                // Get all friends in the friendlist
                var friendList = _messengerManager.GetAllFriendRelationships(_authUserId);
                if (friendList != null)
                {
                    // From here is creating list of friend to return to the UI for render
                    List <FriendRelationshipDTO> friendListDTO = new List <FriendRelationshipDTO>();

                    foreach (FriendRelationship friend in friendList)
                    {
                        friendListDTO.Add(new FriendRelationshipDTO
                        {
                            FriendId       = friend.FriendId,
                            FriendUsername = um.FindUserById(friend.FriendId).UserName
                        });
                    }
                    //string updatedToken = sm.RefreshSession(securityContext.Token);
                    return(Ok(new { friendList = friendListDTO, /*SITtoken = updatedToken */ }));
                }

                else
                {
                    return(Content(HttpStatusCode.NotFound, "User does not have any friend"));
                }
            }
        }
        public IHttpActionResult AddFriendContactList(string addedUsername)
        {
            //The authentication part start from here
            //Create security context from the token
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());;
            }

            //Validate the token
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());;
            }

            //Create authorization manager from security context to check claims
            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );
            // TODO get this from table in database.
            List <string> requiredClaims = new List <string>()
            {
                "CanSendMessage"
            };

            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());;
            }
            else
            {
                UserManager um = new UserManager();

                // Get authUserId from auth username
                _authUserId = um.FindByUserName(securityContext.UserName).Id;
                FriendRelationship friendRelationship = null;
                try
                {
                    // Try to add friend
                    friendRelationship = _messengerManager.AddUserFriendList(_authUserId, addedUsername);
                }

                catch (Exception ex)
                {
                    if (ex is MessageReceiverNotFoundException)
                    {
                        return(Content(HttpStatusCode.NotFound, "User with the username does not exist to be added"));
                    }

                    else if (ex is DuplicatedFriendException)
                    {
                        return(Content(HttpStatusCode.Conflict, "User with the username is already in friend list "));
                    }

                    else if (ex is DbUpdateException)
                    {
                        return(Content(HttpStatusCode.InternalServerError, "There is a error when saving friend relationship to database"));
                    }
                }

                // Create FriendRelationship DTO to return to the front end to render the friendlist
                var friendRelationshipDTO = new FriendRelationshipDTO
                {
                    FriendId       = friendRelationship.FriendId,
                    FriendUsername = um.FindUserById(friendRelationship.FriendId).UserName
                };

                return(Ok(new { friend = friendRelationshipDTO } /*new { SITtoken = updatedToken }*/));
            }

            //string updatedToken = sm.RefreshSession(securityContext.Token);
        }
        //[ActionName("SendMessageExistingConversation")]
        public IHttpActionResult SendMessageWithNewConversation([FromBody] NewConversationMessageDTO newConversationMessageDTO)
        {
            //The authentication part start from here
            //Create security context from the token
            UserManager     um = new UserManager();
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(Request.Headers);

            if (securityContext == null)
            {
                return(Unauthorized());;
            }

            //Validate the token
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());;
            }

            //Create authorization manager from security context to check claims
            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );
            // TODO get this from table in database.
            List <string> requiredClaims = new List <string>()
            {
                "CanSendMessage"
            };

            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());;
            }
            else
            {
                // Find auth user id from auth user name
                _authUserId = um.FindByUserName(securityContext.UserName).Id;
                var authUsername = securityContext.UserName;

                // Find contact user name
                var     contactUser = um.FindByUserName(newConversationMessageDTO.ContactUsername);
                Message returnMessage;

                if (contactUser != null && contactUser.Id != _authUserId)
                {
                    // Map the message to store in database
                    var message = new Message
                    {
                        MessageContent  = newConversationMessageDTO.MessageContent,
                        OutgoingMessage = true,
                        CreatedDate     = DateTime.Now
                    };

                    // Save message to database
                    try
                    {
                        returnMessage = _messengerManager.SaveMessageToDatabase(message, _authUserId, contactUser.Id);
                    }

                    catch (DbUpdateException ex)
                    {
                        return(Content(HttpStatusCode.InternalServerError, "There is an error when saving message to database"));
                    }

                    // Set up SignalR Hub to broadcast the FetchMessage command in receiver
                    var myHub = GlobalHost.ConnectionManager.GetHubContext <MessengerHub>();

                    // Get the message receiver's connection ID to broadcast FetchMessage command to
                    // Lookup by contactId
                    var connectionIDList = _messengerManager.GetConnectionIdWithUserId(contactUser.Id);


                    if (connectionIDList != null)
                    {
                        // When message is saved to database, it will be saved to both auth user's conversation and receiver's conversation
                        //Get the conversation id of the conversation that just receive the new message from auth user.
                        //This conversation is the one belongs to receiver/.
                        int conversationIdToFetchMessage = _messengerManager.GetConversationBetweenUsers(contactUser.Id, _authUserId).Id;

                        //Then broadcast that conversation id to the recever only using connection Id
                        //Then the receiver will know the which conversation that has new message ,and fetch the message
                        foreach (ChatConnectionMapping cM in connectionIDList)
                        {
                            var result = myHub.Clients.Client(cM.ConnectionId).FetchMessages(conversationIdToFetchMessage);
                        }
                        // string updatedToken = sm.RefreshSession(securityContext.Token);
                    }

                    var StoredMessageDTO = new StoredMessageDTO
                    {
                        ConversationId  = returnMessage.ConversationId,
                        OutgoingMessage = true,
                        SenderUsername  = authUsername,
                        MessageContent  = returnMessage.MessageContent,
                        CreatedDate     = returnMessage.CreatedDate,
                    };
                    return(Ok(new { message = StoredMessageDTO } /*new { SITtoken = updatedToken }*/));
                }
                else if (contactUser == null)
                {
                    return(Content(HttpStatusCode.NotFound, "Receiver does not exist to receive message"));
                }

                else if (contactUser.Id == _authUserId)
                {
                    return(Content(HttpStatusCode.Conflict, "You cannot send message to yourself"));
                }
                return(Content(HttpStatusCode.InternalServerError, "There is an error"));
            }
        }
        public IHttpActionResult GetAllConversation()

        {
            //The authentication part start from here
            //Create security context from the token
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());
            }

            //Validate the token
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());
            }

            //Create authorization manager from security context
            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );

            List <string> requiredClaims = new List <string>()
            {
                "CanSendMessage"
            };

            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());
            }
            else
            {
                UserManager um = new UserManager();

                //Get auth User Id from auth username
                _authUserId = um.FindByUserName(securityContext.UserName).Id;

                //Return all conversations of Auth User
                var conversationList = _messengerManager.GetAllConversations(_authUserId);

                //From here, create conversation transfer objects to send to front end
                if (conversationList != null)
                {
                    var conversationDTOList = new List <ConversationDTO>();
                    foreach (Conversation c in conversationList)
                    {
                        var contactUsername = um.FindUserById(c.ContactUserId).UserName;
                        conversationDTOList.Add(new ConversationDTO
                        {
                            Id = c.Id,
                            ContactUsername = contactUsername,
                            HasNewMessage   = c.HasNewMessage,
                            CreatedDate     = c.ModifiedDate.ToString("MMMM dd yyyy hh:mm:ss")
                        });
                    }
                    return(Ok(new { conversations = conversationDTOList, /*SITtoken = updatedToken*/ }));
                }
                return(Content(HttpStatusCode.NotFound, "User does not have any conversation"));
                //string updatedToken = sm.RefreshSession(securityContext.Token);
            }
        }
        public IHttpActionResult GetRecentMessageWithUser(int conversationId2)
        {
            //The authentication part start from here
            //Create security context from the token
            UserManager     um = new UserManager();
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());
            }

            //Validate the token
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());
            }

            //Create authorization manager from security context to check claims
            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );

            List <string> requiredClaims = new List <string>()
            {
                "CanSendMessage"
            };

            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());
            }
            else
            {
                var authUsername = securityContext.UserName;

                //Get conversation between auth user and contact user
                var conversation = _messengerManager.GetConversationFromId(conversationId2);
                if (conversation != null)
                {
                    //Get contact user name
                    var contactUsername = conversation.ContactUsername;

                    //Return the most recent message from the conversation
                    var recentMessage  = _messengerManager.GetRecentMessageBetweenUser(conversationId2);
                    var senderUsername = "";


                    if (recentMessage != null)
                    {
                        //If true , the message is sent from auth user
                        //Set the display username in front end to auth username
                        if (recentMessage.OutgoingMessage == true)
                        {
                            senderUsername = authUsername;
                        }

                        //If false , set the display user name in front end to contactUsername
                        else
                        {
                            senderUsername = contactUsername;
                        }

                        //Create messageDTO for transger
                        var StoredMessageDTO = new StoredMessageDTO
                        {
                            Id             = recentMessage.Id,
                            ConversationId = conversationId2,
                            SenderUsername = senderUsername,
                            MessageContent = recentMessage.MessageContent,
                            CreatedDate    = recentMessage.CreatedDate
                        };

                        //return the message
                        return(Ok(new { message = StoredMessageDTO }));
                    }
                }


                return(Content(HttpStatusCode.NotFound, "No message in conversation"));
            }
        }
        public IHttpActionResult Post(RegistrationData registrationData)
        {
            SecurityContext securityContext = SecurityContextBuilder.CreateSecurityContext(
                Request.Headers
                );

            if (securityContext == null)
            {
                return(Unauthorized());
            }
            SessionManager sm = new SessionManager();

            if (!sm.ValidateSession(securityContext.Token))
            {
                return(Unauthorized());
            }

            AuthorizationManager authorizationManager = new AuthorizationManager(
                securityContext
                );
            // TODO get this from table in database.
            List <string> requiredClaims = new List <string>()
            {
                "CanRegister"
            };

            if (!authorizationManager.CheckClaims(requiredClaims))
            {
                return(Unauthorized());
            }
            else
            {
                UserManager um   = new UserManager();
                Account     user = um.FindByUserName(securityContext.UserName);
                if (user == null)
                {
                    return(NotFound());
                }
                user.FirstName  = registrationData.FirstName;
                user.MiddleName = registrationData.MiddleName;
                user.LastName   = registrationData.LastName;

                // User is a student
                if (registrationData.SchoolId > 0)
                {
                    using (var _db = new DatabaseContext())
                    {
                        ISchoolRegistrationService srs = new SchoolRegistrationService(_db);
                        var school      = srs.FindSchool(registrationData.SchoolId);
                        var domainIndex = user.UserName.IndexOf('@');
                        if (school.EmailDomain.Equals(user.UserName.Substring(domainIndex + 1)))
                        {
                            var     schoolDepartment = srs.FindSchoolDepartment(registrationData.SchoolId, registrationData.DepartmentId);
                            Student student          = new Student(user.Id, schoolDepartment.Id);
                            var     selectedCourses  = srs.GetSchoolTeacherCourses(registrationData.selectedCourseIds);
                            student.Courses = selectedCourses;
                            user.Students.Add(student);
                        }
                        else
                        {
                            return(BadRequest("User's Email Does Not Match School's Email Domain"));
                        }
                    }
                }

                // TODO test this.
                user.DateOfBirth = registrationData.DateOfBirth;
                um.UpdateUserAccount(user);
                if (registrationData.SchoolId > 0)
                {
                    um.SetCategory(user.Id, "Student");
                }
                else
                {
                    um.SetCategory(user.Id, "NonStudent");
                }
                um.RemoveClaimAction(user.Id, "CanRegister");
                um.AutomaticClaimAssigning(user);
                string updatedToken = sm.RefreshSessionUpdatedPayload(
                    securityContext.Token,
                    securityContext.UserId
                    );
                Dictionary <string, string> responseContent = new Dictionary <string, string>()
                {
                    { "SITtoken", updatedToken }
                };
                return(Ok(responseContent));
            }
        }