HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Validating a user

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
uservalidatingstackoverflow

Problem

This works well, but can anybody see any faults in this code? If so, could you suggest ways in which I can fix it?

CREATE PROC ValidateUser
    (
      @Email NVARCHAR(100),
      @PasswordHash NVARCHAR(128)
    )
AS 
    IF EXISTS ( SELECT  1
                FROM    dbo.[User]
                WHERE   [Email] = @Email
                        AND PasswordHash = @PasswordHash ) 
        SELECT  'True' 
    ELSE 
        SELECT  'False'

Solution

The only "fault" I see is that you return "magic strings" as your result - those are always a bit hard to use, and can cause issues (if you misspell a string).

This is a boolean check - you get back True or False - but I would return the boolean values - not strings:

CREATE PROC ValidateUser
    (@Email NVARCHAR(100),
      @PasswordHash NVARCHAR(128))
AS 
    IF EXISTS (SELECT *
               FROM dbo.[User]
               WHERE [Email] = @Email AND PasswordHash = @PasswordHash) 
        SELECT 1
    ELSE 
        SELECT 0


Or the other option would be to just return some column from the users table - if that user exists and the password hash matches, you get back a value - otherwise you get NULL:

CREATE PROC ValidateUser
    (@Email NVARCHAR(100),
      @PasswordHash NVARCHAR(128))
AS 
    SELECT UserID 
    FROM dbo.[User]
    WHERE [Email] = @Email AND PasswordHash = @PasswordHash)


So if the user e-mail and password hash match and exist, then you get back the UserID - otherwise you get NULL. That's also a nice, clear, yes-or-no kind of answer

Code Snippets

CREATE PROC ValidateUser
    (@Email NVARCHAR(100),
      @PasswordHash NVARCHAR(128))
AS 
    IF EXISTS (SELECT *
               FROM dbo.[User]
               WHERE [Email] = @Email AND PasswordHash = @PasswordHash) 
        SELECT 1
    ELSE 
        SELECT 0
CREATE PROC ValidateUser
    (@Email NVARCHAR(100),
      @PasswordHash NVARCHAR(128))
AS 
    SELECT UserID 
    FROM dbo.[User]
    WHERE [Email] = @Email AND PasswordHash = @PasswordHash)

Context

StackExchange Code Review Q#7765, answer score: 7

Revisions (0)

No revisions yet.