/* * Authenticates a user by checking if there is a record in the DB * where the useranme and password match */ private bool AuthenticateUser(User user, out User authedUser, NetworkStream stream) { bool auth = false; User found = null; using (ViaChatEntities db = new ViaChatEntities()) { var query = from u in db.Users where u.username == user.username && u.password == user.password select u; if (query.FirstOrDefault <User>() != null) { auth = true; found = query.FirstOrDefault <User>(); SendResponse(true, "", stream); } else { SendResponse(false, "No user found with those credentials.", stream); } } authedUser = found; return(auth); }
/* * Saves a message in the database */ private bool SaveMessage(Message msg, User user, NetworkStream stream) { bool success = true; byte[] receiveBuffer = new Byte[2]; using (ViaChatEntities db = new ViaChatEntities()) { msg.user_id = user.id; db.Messages.Add(msg); try { db.SaveChanges(); SendResponse(true, "", stream); } catch (Exception e) { success = false; SendResponse(false, e.ToString(), stream); Console.WriteLine(e); } } stream.Read(receiveBuffer, 0, receiveBuffer.Length); //Wait for user to receive message confirmation return(success); }
private User FindUser(string username) { /* * Returns the user having the corresponding username */ using (ViaChatEntities context = new ViaChatEntities()) { var query = from u in context.Users where u.username == username select u; return(query.FirstOrDefault <User>()); } }
private void SendMessageHistory(NetworkStream stream, User authedUser) { ViaChatEntities context = new ViaChatEntities(); byte[] nbMessages = BitConverter.GetBytes(context.Messages.Count <Message>()); stream.Write(nbMessages, 0, nbMessages.Length); //Send number of messages to be read foreach (Message message in context.Messages) { string body = message.body; string username = message.User.id != authedUser.id ? message.User.username : "******"; byte[] historyEntry = Encoding.ASCII.GetBytes(username + ": " + body + "\n"); byte[] receiveBuffer = new Byte[2]; stream.Write(historyEntry, 0, historyEntry.Length); //Writes the message body in the stream //RECEIVE OKAY BEFORE CONTINUING, otherwise the server sends all the messages at once, before the client has time to parse them one by one stream.Read(receiveBuffer, 0, receiveBuffer.Length); } }
/* * Registers a user in the database * Returns true if success */ private bool RegisterUser(User user, NetworkStream stream) { bool success = true; using (ViaChatEntities db = new ViaChatEntities()) { db.Users.Add(user); try { db.SaveChanges(); SendResponse(true, "", stream); } catch (Exception e) { success = false; SendResponse(false, e.ToString(), stream); Console.WriteLine(e); } } return(success); }