Recent Entries 10
- pattern minor 112d agoAuthenticating and redirecting six specific usersIn a project I have a few long switch statements which seem ugly to me. Please suggest how to refactor the following code. ``` protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); switch(username) { case "client1": if(PASSWORD.equals(password)) { request.getSession(true).setAttribute("username", username); response.sendRedirect("app1/apk-1-index.html"); } break; case "client2": if(PASSWORD.equals(password)) { request.getSession(true).setAttribute("username", username); response.sendRedirect("app2/apk-2-index.html"); } break; case "client3": if(PASSWORD.equals(password)) { request.getSession(true).setAttribute("username", username); response.sendRedirect("app3/apk-3-index.html"); } break; case "client4": if(PASSWORD.equals(password)) { request.getSession(true).setAttribute("username", username); response.sendRedirect("app4/apk-4-index.html"); } break; case "client5": if(PASSWORD.equals(password)) { request.getSession(true).setAttribute("username", username); response.sendRedirect("app5/apk-5-index.html"); } break; case "client6": if(PASSWORD.equals(password)) { request.getSession(true).setAttribute("username", username); response.sendRedirect("app5/apk-5-index.html"); } break; default: response.sendRedirect("/Test2/index.jsp"); } } ```
- pattern minor 112d agoAngular Guards - Firebase loggedInAndVerifiedI have an app that I want to limit to both logged in and verified users. I was able to make two separate guards (`logged-in.guard.ts` and `verified.guard.ts`), but since one guard was dependant on the other guard, I made a third guard that combined the two (`logged-in-and-verified.guard.ts`). I appreciate any feedback, because I am new to angular guards; specifically, is there a better way to do this? It seemed a bit convoluted to me. The code does work currently. logged-in.guard.ts ``` import {Injectable} from '@angular/core'; import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router'; import {Observable} from 'rxjs/Observable'; import {AngularFireAuth} from 'angularfire2/auth'; import * as firebase from 'firebase/app'; @Injectable() export class LoggedInGuard implements CanActivate { user: Observable; constructor(private auth: AngularFireAuth, private router: Router) { this.user = auth.authState; } canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { const url = state.url; // store current url return this.checkLogin(); } checkLogin(): Observable { let loggedIn; return this.user.map(u => { loggedIn = !!u; // if u, return true, else return false if (loggedIn) { return true; } else { // re-route them to the login page this.router.navigate(['/login']); return false; } }); } } ``` verified.guard.ts ``` import {Injectable} from '@angular/core'; import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router'; import {Observable} from 'rxjs/Observable'; import {AngularFireAuth} from 'angularfire2/auth'; import {AngularFireDatabase} from 'angularfire2/database'; @Injectable() export class VerifiedGuard implements CanActivate { loggedIn: boolean; constructor(private afAuth: AngularFireAuth, private db: AngularFireDatabase) { } canActivate(next: Act
- pattern minor 112d agoSimple log-in to systemI am fairly new to the MVC paradigm and I am working with Swing at the moment. To test my understanding of MVC, I have written this simple program used to login in to a system. I was hoping someone could review what I have done so far and let me know if it follows MVC rules and best practices. The View: ``` public class LoginScreen extends JFrame implements Observer { private JLabel lblTitle, lblUsername, lblPassword; private JTextField txtVanReg; private JPasswordField txtPassword; private JPanel pnlCenter, pnlNorth; private JButton btnLogin, btnCancel; private final Font fntOther = new Font("Verdana", Font.PLAIN, 16); private final Font fntTitle = new Font("Verdana", Font.PLAIN, 20); private LoginController controller; public LoginScreen() { this.controller = new LoginController(this); this.setTitle("Login"); this.setLayout(new BorderLayout()); setUpComponents(); } private void setUpComponents() { lblTitle = new JLabel("Burrito Business"); lblUsername = new JLabel("Van reg: "); lblPassword = new JLabel("Password: "); txtVanReg = new JTextField(); txtPassword = new JPasswordField(); btnLogin = new JButton("Login"); btnCancel = new JButton("Cancel"); btnLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { controller.loginRequested(txtVanReg.getText(), txtPassword.getPassword()); } }); btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { controller.loginCancelled(); } }); pnlCenter = new JPanel(new GridLayout(3, 3)); pnlNorth = new JPanel(new BorderLayout()); pnlCenter.add(lblUsername); pnlCenter.add(txtVanReg); pnlCenter.add(lblPassword); pnlCenter.add(txtPassword); pnlCenter.add(btnLogin); pnlCenter.add(btnCancel); pnlNorth.add(lblTitle); setFonts(); this.add(pnlNorth, BorderLayout.NORTH); this.add(pnlCente
- pattern minor 112d agoLogin window in Swing using MVPI am trying to grasp MVP (like so many) and although there are quite a few resources out there, I'm not sure I really get it. I am trying to do this without frameworks to really see what's going on. Here's my code: main method (only method in a special class called `Main`): ``` SwingUtilities.invokeLater(() -> { JFrame mainWindow = new JFrame(); mainWindow = new JFrame("MainFenster"); mainWindow.setSize(500, 500); mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainWindow.setLocationRelativeTo(null); mainWindow.setLayout(new BorderLayout()); LoginView loginView = new SwingLoginView(mainWindow); LoginModel loginModel = new LoginModelImpl(); LoginService loginService = new LoginServiceImpl(loginModel); LoginPresenter presenter = new LoginPresenter(loginView, loginService); loginView.setPresenter(presenter); mainWindow.setVisible(true); }); ``` View interfaces ``` public interface View { // Not sure what woudl go here, but just in case... } public interface LoginView extends View { void setErrorMessage(String errorMessage); void setNotificationMessage(String message); void navigateToHome(); // Should go here? void setPresenter(LoginPresenter presenter); interface LoginViewEventListener { void loginButtonClicked(String username, String password); } } public class SwingLoginView implements LoginView { private JFrame mainFrame; private LoginPresenter presenter; private JTextArea errorMessage; private JTextArea password; private JTextArea username; private JTextArea notificationMessage; private JPanel panel; public SwingLoginView(JFrame mainWindow) { this.mainFrame = mainWindow; inititialize(); } private void inititialize() { initializeComponents(); } private void initializeComponents() { errorMessage = new JTextArea(); errorMessage.setText("Hello"); notification
- pattern minor 112d agoExpress routing with a login action using SQLiteI'm new to Express and SQL, so I don't know the conventional ways of combining the two. Right now I have done it the following way: ``` app.get('/login', function (req, res) { res.render('login'); }); app.get('/home', function (req, res) { res.render('home'); }); app.post('/login', function (req, res) { db = new sqlite3.Database(file); db.serialize(function () { [...] db.all(query, function (err, rows) { if(rows.length == 1) { [...] res.render('home', { username: rows[0].username }); } else { res.render('login', { message: "Login not successful!" }); } }); }); db.close(); }); ``` However, I feel like the routing should be separated from the database stuff. What should I do different? Or is this normal?
- pattern major 112d agoLogin form C# SQLBasically this is my first login form. I am using SQL and C# WinForms. I made user roles such as "Admin" and others and the user is taken to a specific WinForms, according to his appointed role (appointed by me manually now). I have also allowed users to create their new accounts, in which they pick their user name and password but the role still needs to be appointed by me. I'd like to know if what I've done is ok or if it needs improvement, and where. ``` namespace My_PROGRAM { public partial class Login : Form { SqlConnection loginCon = new SqlConnection("Data Source=******;Initial Catalog=***;Persist Security Info=True;User ID=*****;Password=**********"); public Login() { InitializeComponent(); } private void btnLogin_Click(object sender, EventArgs e) { loginCon.Open(); SqlDataAdapter loginAdapter = new SqlDataAdapter("SELECT [Role] FROM [dbo].[LOGIN_Tab] WHERE Name ='"+ userNameTextobx.Text +"' and Password='"+ userPasswordTextbox.Text +"' ", loginCon); DataTable result = new DataTable(); loginAdapter.Fill(result); try { if (result.Rows.Count == 1) { switch(result.Rows[0]["Role"] as string) { case "Admin": { this.Hide(); AdminMenu aMenu = new AdminMenu(); MessageBox.Show("Login was succesful. Welcome back " + userNameTextobx.Text + " !!"); aMenu.Show(); break; } case "Planner": { this.Hide(); PlannerMenu pMenu = new PlannerMenu(); MessageBox.Show("Login was succesfu
- pattern minor 112d agoMaking a "remember login" functionI'm trying to make a safe "remember me / auto login" function on my site and as I'm just a hobby programmer I would like someone professional to take a look at my code this far. This site will probably never see the light of day I'm just doing this because I find it fun and learning, but I still like to do it correct. I have read this. Login.php ``` $query = $db->prepare('SELECT id, username, password FROM users WHERE username = ? OR email = ?'); $query->execute(array($_POST['username'], $_POST['username'])); $row = $query->fetch(); if ($row and password_verify($_POST['password'], $row['password'])) { // Remember? if (isset($_POST['remember'])) { $selector = base64_encode(random_bytes(9)); $authenticator = random_bytes(33); setcookie('remember', $selector.':'.base64_encode($authenticator), time() + 864000); $query = $db->prepare('INSERT INTO auth_tokens (selector, token, userid, expires) VALUES (?, ?, ?, ?)'); $query->execute(array( $selector, hash('sha256', $authenticator), $row['id'], date('Y-m-d\TH:i:s', time() + 864000) )); } $_SESSION['userid'] = $row['id']; $_SESSION['username'] = $row['username']; exit(header('Location: /')); } ``` This is my logout: ``` session_destroy(); if (!empty($_COOKIE['remember'])) { setcookie('remember', '', time() - 1000); $db->exec('DELETE FROM auth_tokens WHERE userid = '.$_SESSION['userid']); } exit(header('Location: '.SITE_URL)); ``` And this is my code in index.php to check if the user has the cookie and log them in: ``` if (empty($_SESSION['userid']) && !empty($_COOKIE['remember'])) { list($selector, $authenticator) = explode(':', $_COOKIE['remember']); $query = $db->prepare('SELECT * FROM auth_tokens WHERE selector = ?'); $query->execute(array($selector)); $row = $query->fetch(); if (hash_equals($row['token'], hash('sha256', base64_decode($authenticator)))) { $_SESSION['userid'] = $row['userid']; } }
- pattern minor 112d agoLogin program in PythonI wrote this login program as part of my project for school. Should I use my implementation of a login program, or is there some standardized patterns of login programs, like the ones in encryption where we use made packages instead of writing our own? Also, please correct me if am doing anything wrong or if there is a faster and more elegant way. ``` users = [] """ Look of data.txt john|mckinly|tree|ssap321 elie|rose|sweet|pass123 """ def loadData(): with open('data.txt','r') as data: for line in data: user = makeUser(line) users.append(user) return True def saveData(): with open('data.txt','w') as data: for user in users: print(user['name']+'|'+user['surname']+'|'+user['username']+'|'+user['password'],file = data) def makeUser(line): name, surname, username, password = line.split('|') if password[-1:] == '\n': password = password[:-1] return {'name':name, 'surname':surname, 'username':username, 'password':password } def register(): name = input('Name:') surname = input('Surname:') while True: username = input('Username:') if checkLen(username): break while True: password = input('Password:') if checkLen(password): break users.append({'name':name,'surname':surname,'username':username,'password':password}) def checkLen(info): if len(info) > 0: return True else: print('Can\'t be blank!') def login(state): while state: username = input('Username:') password = input('Password:') for user in users: if user['username'] == username and user['password'] == password: print('You are logged in.') state = False break else: print('Wrong input.') def main(): state = loadData() print('1) Login') print('2)
- pattern minor 112d agoFiltering ASP.NET membership roles without the default attributesI am building an application, and I needed an attribute similar to `AuthorizeAttribute`, supporting `Roles` but not using the `MembershipProvider` roles. (Basically, with the setup I have, I cannot rely on the `User.IsInRole` method - it's not always accurate, so I manually query the roles in my `MasterDbContext` instead.) I have two different parts to it: ``` public class RequiredRoleAttribute : FilterAttribute, IAuthorizationFilter { public string Roles { get; set; } public string Destination { get; set; } = "~/Account/Login"; public void OnAuthorization(AuthorizationContext filterContext) { var context = new MasterDbContext(); var user = context.Users.Find(filterContext.HttpContext.User.Identity.GetUserId()); var requiredRoles = Roles.Split(',').Select(roleName => context.Roles.First(role => role.Name == roleName).Name).ToList(); if (!requiredRoles.All(r => user.InRole(r, context))) { if (Destination == null) { filterContext.Result = new RedirectToRouteResult("Default", null); } else { filterContext.Result = new RedirectResult(Destination); } } } } ``` This should be self-explanatory. It does the same thing as `[AuthorizeAttribute(Roles = "SomeString")]`, used in conjunction with that attribute: ``` [Authorize] [RequiredRole(Roles = Constants.Roles.Moderators)] public abstract class BaseController : Controller { public MasterDbContext Context { get; } = new MasterDbContext(); } ``` So that's easy. As you can see, I can still use `[Authorize]`, I just can't use `[Authorize(Roles = ...)]`. Then, I wrote `User.InRole` instead of the `User.IsInRole` method: ``` public bool InRole(string roleName, MasterDbContext providedContext = null) { var context = providedContext ?? new MasterDbContext(); var roleId = context.Roles.First(r => r.Name == roleName).Id; return Roles.ToList
- pattern minor 112d agoPrompting user for connection parameters to SQL ServerI try to avoid keeping passwords etc. in memory or in plain text anywhere. But I am on a huge time crunch and this will only be used internally this week then probably won't get touched again. I just want to make sure this is secure and if not, what the risk is. I'm mostly concerned about the password sitting in memory. I'm not sanitizing data but for this particular case it isn't needed. My specific questions are: - From a security perspective, would this code be acceptable in a SQL Importer? - Besides data sanitation, is there a best practice somewhere that I'm missing in this? ``` Console.WriteLine("Enter the Server Name. Ex: SQLMASTER"); //Gets the server to connect to, an IP address is also acceptable. ServerName = Console.ReadLine(); Console.WriteLine("Enter the Database. Ex: Accounts"); //The actual database to use. DatabaseName = Console.ReadLine(); Console.WriteLine("Use Windows authentication? Y/N"); //you will usually use this. YesNo = Console.ReadLine(); if (YesNo.ToLower() != "y") { Console.WriteLine("Enter your Username (Domain name may be required). Ex: MyName"); UserName = Console.ReadLine(); Console.WriteLine("Enter your Password. Ex: ********"); Password = ReadPassword(); //Builds the connection string with the data we collected above. We're going to send this to the SQL Connection. (Username and Password) ConnectionString = "Data Source = " + ServerName + "; Initial Catalog = " + DatabaseName + "; User ID = " + UserName + "; Password = " + Password; Password = ""; //We do this to clear the password from memory UserName = ""; //Clearing username from memory } else { //Builds the connection string with the data we collected above. We're going to send this to the SQL Connection. (Windows Authentication) ConnectionString = "Data Source = " + ServerName + "; Initial Catalog = " + DatabaseName + "; Integrated Security=SSPI"; //User ID = " + UserName + "; Password = " + Password; } //Create a new connec