What's wrong with this Registration stored procedure - sql-server

I'm trying to make a Registration stored procedure and when I execute the code, I get this error. I've googled it but it's more specific message error was not able to find a solution. what can cause issue here? Thanks in advice!
Error:
Msg 156, Level 15, State 1, Procedure SP_Registration, Line 39 [Batch Start Line 9]
Incorrect syntax near the keyword 'SET'.
This is my stored procedure:
-- =============================================
-- Author: <Nika Kalatozi>
-- Create date: <04/07/2017>
-- Description: <Registration Stored Procedure>
-- =============================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SP_Registration]
#Username NVARCHAR(25),
#Password NVARCHAR(30),
#Email NVARCHAR(35),
#Firstname NVARCHAR(25),
#Lastname NVARCHAR(25),
#Gender NVARCHAR(10),
#Birthdate DATE,
#PhoneNumber NVARCHAR(25),
#PersonalID NVARCHAR(11),
#Result VARCHAR(100) OUTPUT
AS
BEGIN
IF EXISTS(SELECT #Username FROM Users WHERE #Username = #Username)
BEGIN
SET #Result = 'The username you have entered is already in use.'
RETURN;
END
ELSE IF EXISTS(SELECT #Email FROM Users WHERE #Email = #Email)
BEGIN
SET #Result = 'The email you have entered is already in use.'
RETURN;
END
ELSE
BEGIN
INSERT INTO Users(Username, [Password], Email, Firstname, Lastname,
Gender, BirthDate, PhoneNumber, PersonalID)
SET #Result = 'You have been registered successfully.'
RETURN;
END
END

In code
INSERT INTO Users(
...
)
you should specify what to insert:
INSERT INTO Users(
...
) VALUES
(#Username, ...) -- specify values in brakets

Related

Creating procedure to login with password hashed and salt, returning Incorrect password

Ok, so I am making an ASP.net website application that has a registration form that will take in details about the user and the password will be encrypted with a registration procedure that will hash and salt the password. Now the problem is that when creating a login procedure. The login procedure that I implemented is displaying "Incorrect password" on #responseMessage output when passing in the username and password. What could be the problem and how to fix this issue?
RestuarantProc - Registration Procedure
CREATE PROCEDURE [dbo].[RestuarantProc]
#FirstName NVARCHAR(50),
#LastName NVARCHAR(50),
#UserName NVARCHAR(50),
#Password NVARCHAR(50),
#Age INT,
#Email VARCHAR(100),
#responseMessage NVARCHAR(250) OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE #salt UNIQUEIDENTIFIER=NEWID()
BEGIN TRY
INSERT INTO RestuarantReg(FirstName, LastName, UserName, PasswordHash, PasswordSalt, Age, Email)
VALUES(#FirstName, #LastName, #UserName, HASHBYTES('SHA2_512', #Password+CAST(#salt AS NVARCHAR(36))),
#salt, #Age, #Email)
SET #responseMessage='Success'
END TRY
BEGIN CATCH
SET #responseMessage=ERROR_MESSAGE()
END CATCH
END
GO
DECLARE #responseMessage NVARCHAR(250)
EXEC dbo.RestuarantProc #FirstName = 'Bob', #LastName = 'Hudgins', #UserName = 'bobh123', #Password = 'password',
#Age = '23', #Email = 'bob#bob.com', #responseMessage = #responseMessage OUTPUT
SELECT * FROM RestuarantReg
RestuarantProcLogin - Login Procedure
CREATE PROCEDURE RestuarantProcLogin
#userName NVARCHAR(254),
#password NVARCHAR(50),
#responseMessage NVARCHAR(250)='' OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE #userID INT
IF EXISTS (SELECT TOP 1 Id FROM [dbo].[RestuarantReg] WHERE UserName=#userName)
BEGIN
SET #userID=(SELECT Id FROM [dbo].[RestuarantReg]
WHERE UserName=#userName AND
PasswordHash=HASHBYTES('SHA2_512', #password+CAST(PasswordSalt AS NVARCHAR(36))))
IF(#userID IS NULL)
SET #responseMessage='Incorrect password'
ELSE
SET #responseMessage='User successfully logged in'
END
ELSE
SET #responseMessage='Invalid login'
END
DECLARE #responseMessage nvarchar(250)
EXEC dbo.RestuarantProcLogin #userName = N'bobh123', #password = N'password', #responseMessage = #responseMessage OUTPUT
SELECT #responseMessage as N'#responseMessage'
Move the calculation of the hash into a function. Easy to do, easy to maintain, single point of definition. Problem solved if you keep the datastore for your vars the same as your table.

Stored Procedure For Updating Records And Deleting Records Using Dynamic SQL

I have a stored procedure that inserts records into the specified schema table using dynamic sql. To specify which schema you would like to insert into, it is done as follows:
EXEC Stored_Procedure_Name '[Schema_Name]', 'value1', 'value2', ...
The problem that I now face is that I wish to have a similar stored procedure that updates the table within a specified schema, as well as delete records within a specified schema's table, but I can't wrap my head around a method to accomplish this.
I've tried changing the code to make it UPDATE (instead of INSERT INTO) the tables but the logic behind it doesn't make any sense.
if object_id('AddUser_proc', 'AU') is not null
begin
drop proc AddUser_proc;
end;
GO
CREATE PROCEDURE AddUser_proc
(#branch VARCHAR(50),
#UserID NUMERIC(13,0),
#Username VARCHAR(50),
#Email VARCHAR(50),
#Fullname VARCHAR(100),
#Password BINARY(64),
#DateCreated DATETIME,
#ClosestBranch VARCHAR(50) )
AS
BEGIN
IF EXISTS(
SELECT 1
FROM Sys.Schemas
WHERE name = #branch
)
BEGIN
DECLARE #dynamic nvarchar(4000),
#paramDefinition nvarchar(4000)
SELECT #dynamic = N'INSERT INTO '+ quotename(#branch) + N'.User_tbl (
UserID,
Username,
Email,
Fullname,
Password,
DateCreated,
ClosestBranch
)
VALUES(#UserID, #Username, #Email, #Fullname, #Password, #DateCreated, #ClosestBranch)',
#paramDefinition =
N'#UserID numeric(13,0),
#Username varchar(50),
#Email varchar(50),
#Fullname varchar(100),
#Password binary(64),
#DateCreated datetime,
#ClosestBranch varchar(50)'
EXEC sp_executeSql #dynamic, #paramDefinition, #UserID, #Username, #Email, #Fullname, #Password,
#DateCreated, #ClosestBranch;
END
END
GO
Above is the code I have for the INSERT stored procedure. I would appreciate it if you could help me with a similar stored procedure that updates tables, as well as one that deletes records from tables. It would be ideal if all three (INSERT, UPDATE and DELETE) procedures could be contained within one stored procedure with the use of IF statements.
EDITED:
This is the SP that I have:
if object_id('UpdateUser_proc', 'UU') is not null
begin
drop proc UpdateUser_proc;
end;
GO
CREATE PROCEDURE UpdateUser_proc(
#branch varchar(50),
#UserID numeric(13,0),
#Username varchar(50),
#Email varchar(50),
#Fullname varchar(100),
#Password binary(64),
#DateCreated datetime,
#ClosestBranch varchar(50)
)
AS
BEGIN
IF EXISTS(
SELECT 1
FROM Sys.Schemas
WHERE name = #branch
)
BEGIN
DECLARE #dynamic nvarchar(4000),
#paramDefinition nvarchar(4000)
SELECT #dynamic = N'UPDATE '+ quotename(#branch) + N'.User_tbl
SET Username=#Username,Email=#Email,Fullname=#Fullname,Password=#Password,DateCreated=#DateCreated,ClosestBranch=#ClosestBranch
WHERE UserID=#UserID',
#paramDefinition =
N'#UserID numeric(13,0),
#Username varchar(50),
#Email varchar(50),
#Fullname varchar(100),
#Password binary(64),
#DateCreated datetime,
#ClosestBranch varchar(50)'
EXEC sp_executeSql #dynamic, #paramDefinition, #UserID, #Username, #Email, #Fullname, #Password,
#DateCreated, #ClosestBranch;
END
END
GO
And I execute it like so:
EXEC UpdateUser_proc 'Bloemfontein', '7928623003512', 'klover', 'test.g#g.com', 'John Snow', 'password', '20190303', 'Bloemfontein'
I have discovered that the problem may be due to the fact that the password field is a binary(64) type and I can't seem to use the HASHBYTES function within execution of the SP
As far as the DELETE SP goes, I have not attempted it yet as I have been stuck with the UPDATE SP.

Incorrect syntax error sql

CREATE PROC CreateOrUpdate
#ID INT,
#NRIC VARCHAR(50),
#Name VARCHAR(50),
#Description VARCHAR(50),
#Location1 VARCHAR(50)
AS
BEGIN
IF (#ID = 0)
BEGIN
INSERT INTO tblBlacklist (NRIC, Name, Description, createdatetime, Location1)
VALUES (#NRIC, #Name, #Description, GETDATE(), #Location1)
END
ELSE
BEGIN
UPDATE tblBlacklist
SET NRIC = #NRIC,
Name = #Name,
Description = #Description,
createdatetime = GETDATE()
WHERE ID = #ID
AND Location1 = #Location1
END
END
/****** Object: StoredProcedure [dbo].[ContactViewAll] Script Date: 15-
Apr-2017 7:39:13 AM ******/
CREATE PROC ViewAll
#Location1 VARCHAR(50)
AS
BEGIN
SELECT *
FROM tblBlacklist
WHERE Location1 = #Location1
END
I cannot see any errors within my coding. The error message is
Msg 156, Level 15, State 1, Procedure CreateOrUpdate, Line 28 [Batch Start Line 0]
Incorrect syntax near the keyword 'PROC'
Please help me thanks.
One suggestion is to add a go between your two create statements, and remove the system comment:
CREATE PROC CreateOrUpdate
#ID int,
#NRIC varchar(50),
#Name varchar(50),
#Description varchar(50),
#Location1 varchar(50)
AS
BEGIN
IF(#ID=0)
BEGIN
INSERT INTO tblBlacklist(NRIC,Name,Description,createdatetime,Location1)
VALUES(#NRIC,#Name,#Description,getdate(),#Location1)
END
ELSE
BEGIN
UPDATE tblBlacklist
SET
NRIC = #NRIC,
Name = #Name,
Description = #Description,
createdatetime = getdate()
WHERE ID= #ID and Location1=#Location1
END
END
GO
CREATE PROC ViewAll
#Location1 varchar(50)
AS
BEGIN
SELECT *
FROM tblBlacklist
WHERE Location1 = #Location1
END
GO
try surround your input parameters inside fitst brace ()

Authenticate user in stored procedure

I am new to sql and I am not sure what's wrong with my stored procedure.
User inputs user name & password which are my input parameters and if it is correct then return 'Login Success', if UN is incorrect than return 'Incorrect UN' or if PW is incorrect than return 'Incorrect PW'. In the stored procedure I have an IF Else statement and it is only hitting the first IF statement not other.
Please have a look my stored procedure:
CREATE PROCEDURE [dbo].[AuthenticateUser]
#UserName varchar(15),
#Password varchar(15),
#Role varchar(25) OUTPUT
AS
SET NOCOUNT ON
BEGIN
DECLARE #UN VARCHAR(25)
DECLARE #PW VARCHAR(25)
SELECT #UN = UserName, #PW = Password FROM LogIn
IF (#UN != #UserName COLLATE SQL_Latin1_General_CP1_CS_AS)
BEGIN
SET #Role = 'Incorrect User Name'
END
ELSE
BEGIN
IF (#PW != #Password COLLATE SQL_Latin1_General_CP1_CS_AS)
BEGIN
SET #Role = 'Incorrect Password'
END
ELSE
BEGIN
SET #Role = 'Logged in Successfully'
END
END
SELECT #Role
END
Thank you for your help
You are doing this:
SELECT #UN = UserName, #PW = Password FROM LogIn
IF (#UN != #UserName COLLATE SQL_Latin1_General_CP1_CS_AS)
These comparisions #UN = UserName and #PW = Password should be made in the WHERE clause to help in proper filtering of rows.
Here is the code rewritten (you can change to using your own table name)
Drop Table TestLogin
GO
Create Table TestLogin
(
UserName VarChar (20),
Password VarChar(20)
)
Insert TestLogin Values ('One', 'Two')
GO
Drop PROCEDURE AuthenticateUser
GO
CREATE PROCEDURE AuthenticateUser
#UserName varchar(15),
#Password varchar(15),
#Role varchar(25) OUTPUT
AS
If ((SELECT Count (*) From TestLogin Where UserName COLLATE SQL_Latin1_General_CP1_CS_AS = #Username And Password COLLATE SQL_Latin1_General_CP1_CS_AS = #Password) = 0)
Begin
If ((SELECT Count (*) From TestLogin Where UserName COLLATE SQL_Latin1_General_CP1_CS_AS = #Username) = 0)
Begin
Select #Role = 'Incorrect User Name'
End
Else
Begin
Select #Role = 'Incorrect Password'
End
End
Else
Begin
Select #Role = 'Logged in Successfully'
End
GO
Declare #Role VarChar (100)
Exec AuthenticateUser 'One', 'Two', #Role Output
Print #Role
Exec AuthenticateUser 'One', 'TwoX', #Role Output
Print #Role
Exec AuthenticateUser 'OneX', 'Two', #Role Output
Print #Role
The three examples provided at the end show you how the procedure behaves when you give it a good login, or either parameter is incorrect.
Change it to a SELECT COUNT(1) FROM userLogin.... and then use ExecuteScalar() on the SqlDataReader object.
As a side note, it's not a good idea to store your passwords in the DB in plain text, but hash them instead, preferably with a salt value.
Try this instead:
Create PROCEDURE [dbo].[AuthenticateUser]
#UserName varchar(15),
#Password varchar(15),
#Role varchar(25) OUTPUT
AS
SET NOCOUNT ON
BEGIN
If Not Exists (Select 1 From LogIn Where UserName = #UserName) Set #Role = 'Incorrect UserName'
Else If Not Exists (Select 1 From LogIn Where Password = #Password) Set #Role = 'Incorrect Password'
Else Set #Role = 'Logged in Successfully'
Select #Role
END
Generally it is not good idea to give an attacker a cue "name is OK, now guess PWD". Plus, password should be at least case sensitive. For this purpose:
select #un=username from LogIn
where username=#username
and cast(password as varbinary(max)) = cast(#password as varbinary(max))
if #un is null
set #role = 'UN or PWD is incorrect'
else
set #role = 'Success'
If you want to give hints:
select #un=username from LogIn
where username=#username
if #un is null
set #role = 'UN not found'
else
begin
select #un=username from LogIn
where username=#username
and cast(password as varbinary(max)) = cast(#password as varbinary(max))
if #un is null
set #role = 'password incorrect'
else
set #role = 'Success'
end
P.S.: I hope username is unique in your table.

Stored procedure that creates a user profile and look up if value exist in other tables

I have a stored procedure that creates a user profile, my form has the following fields:
FirstName,
LastName.
EmailAddress,
ZipCode,
Password
The zip code is a FK in my UserProfile of type smallint the value may or may not already exist in a table called Location:
LocationId bigInt (identity index)
ZipCode smallint
Is there a way from within my stored procedure to query that table, if the item exist use the PK of that entry in my stored procedure ?
This is my stored procedure so far
CREATE PROCEDURE [dbo].[SP_InsertInitialProfile]
#FirstName NVARCHAR(1000),
#LastName NVARCHAR(1000),
#EmailAddress NVARCHAR(1000),
#ZipCode SMALLINT,
#Password NVARCHAR(1000)
AS
IF (SELECT COUNT(1) FROM UserProfile WHERE EmailAddress =#EmailAddress) = 1
BEGIN
RETURN -1
END ELSE
BEGIN
INSERT INTO UserProfile(FirstName,LastName,EmailAddress,Password)
VALUES(#FirstName,#LastName,#EmailAddress,#Password)
RETURN Cast(##IDENTITY as INT)
END
You can do SP like this:
CREATE PROCEDURE [dbo].[SP_InsertInitialProfile]
#FirstName NVARCHAR(1000),
#LastName NVARCHAR(1000),
#EmailAddress NVARCHAR(1000),
#ZipCode SMALLINT,
#Password NVARCHAR(1000)
AS
varCountNbr number;
BEGIN
SELECT COUNT(1) INTO varCountNbr
FROM
Location
WHERE
ZipCode=#ZipCode;
IF varCountNbr = 0
INSERT #ZipCode INTO Location TABLE;
-- You have to commit here, in order to have the PK value exists.
COMMIT;
INSERT INTO USERPROFILE TABLE;
COMMIT;
END;

Resources