Skip to content

Commit 599720e

Browse files
authored
feat: password authentication (#82)
1 parent a32caa8 commit 599720e

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

redis.ts

+10
Original file line numberDiff line numberDiff line change
@@ -1462,6 +1462,7 @@ export type RedisConnectOptions = {
14621462
port?: number | string;
14631463
tls?: boolean;
14641464
db?: number;
1465+
password?: string;
14651466
};
14661467

14671468
function prasePortLike(port: string | number | undefined): number {
@@ -1488,6 +1489,7 @@ export async function connect({
14881489
port,
14891490
tls,
14901491
db,
1492+
password,
14911493
}: RedisConnectOptions): Promise<Redis> {
14921494
const dialOpts: Deno.ConnectOptions = {
14931495
hostname,
@@ -1504,6 +1506,14 @@ export async function connect({
15041506
const bufw = new BufWriter(conn);
15051507
const exec = muxExecutor(bufr, bufw);
15061508
const client = await create(conn, conn, conn, exec);
1509+
if (password != null) {
1510+
try {
1511+
await client.auth(password);
1512+
} catch (err) {
1513+
client.close();
1514+
throw err;
1515+
}
1516+
}
15071517
if (db) {
15081518
await client.select(db);
15091519
}

tests/general_test.ts

+21
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import {
44
assertThrowsAsync,
55
} from "../vendor/https/deno.land/std/testing/asserts.ts";
66
import { makeTest } from "./test_util.ts";
7+
import { ErrorReplyError } from "../errors.ts";
8+
import { Redis } from "../redis.ts";
79

810
const { test, client: redis, opts } = await makeTest("general");
911
test("conccurent", async function testConcurrent() {
@@ -35,6 +37,25 @@ test("db0", async function testDb0Option() {
3537
client2.close();
3638
});
3739

40+
test("connect with wrong password", async function testConnectWithWrongPassword() {
41+
await assertThrowsAsync(async () => {
42+
await connect({
43+
...opts,
44+
password: "wrong_password",
45+
});
46+
}, ErrorReplyError);
47+
});
48+
49+
test("connect with empty password", async function testConnectWithEmptyPassword() {
50+
// In Redis, authentication with an empty password will always fail.
51+
await assertThrowsAsync(async () => {
52+
await connect({
53+
...opts,
54+
password: "",
55+
});
56+
}, ErrorReplyError);
57+
});
58+
3859
test("exists", async function testDb1Option() {
3960
const key = "exists";
4061
const client1 = await connect({ ...opts, db: 0 });

0 commit comments

Comments
 (0)