forked from base/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgen-apikey.sh
More file actions
executable file
Β·140 lines (111 loc) Β· 2.52 KB
/
Copy pathgen-apikey.sh
File metadata and controls
executable file
Β·140 lines (111 loc) Β· 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#!/usr/bin/env bash
set -euo pipefail
FILE="./nginx/api_keys.map"
DELETED_FILE="./nginx/api_keys.deleted"
mkdir -p "$(dirname "$FILE")"
# Ensure files exist
touch "$FILE"
touch "$DELETED_FILE"
usage() {
echo "Usage:"
echo " $0 add <name> <comment>"
echo " $0 del <line_number>"
echo " $0 list"
exit 1
}
validate_name() {
[[ "$1" =~ ^[a-zA-Z0-9-]{1,9}$ ]]
}
nginx_safe_reload() {
if nginx -t; then
nginx -s reload
echo "π nginx reloaded"
else
echo "β nginx config invalid, NOT reloaded"
exit 1
fi
}
add_key() {
local name="$1"
local comment="${2:-}"
if ! validate_name "$name"; then
echo "β Invalid name. Must be <=9 chars, only letters/numbers/dash."
exit 1
fi
local key="${name}-$(openssl rand -hex 22)"
# prevent duplicates
if grep -q "^${key} " "$FILE"; then
echo "β Key already exists"
exit 1
fi
echo "${key} 1; # ${comment}" >> "$FILE"
echo "β
Added key:"
echo "${key}"
echo ""
nginx_safe_reload
}
delete_key() {
local line="$1"
if ! [[ "$line" =~ ^[0-9]+$ ]]; then
echo "β Line number must be numeric"
exit 1
fi
if [[ ! -s "$FILE" ]]; then
echo "β File is empty"
exit 1
fi
local total
total=$(wc -l < "$FILE")
if (( line < 1 || line > total )); then
echo "β Invalid line number (1-$total)"
exit 1
fi
local entry
entry=$(sed -n "${line}p" "$FILE")
# append to deleted file
echo "$entry" >> "$DELETED_FILE"
# remove line
if sed --version >/dev/null 2>&1; then
# GNU sed (Linux)
sed -i "${line}d" "$FILE"
else
# BSD sed (macOS)
sed -i '' "${line}d" "$FILE"
fi
echo "ποΈ Deleted line $line"
echo "$entry"
echo ""
nginx_safe_reload
}
list_keys() {
if [[ ! -s "$FILE" ]]; then
echo "β οΈ No keys found"
exit 0
fi
echo "π API Keys:"
echo "----------------------------------------"
# custom numbered clean output
local i=1
while IFS= read -r line; do
echo "$i) $line"
((i++))
done < "$FILE"
echo "----------------------------------------"
echo "Total: $(wc -l < "$FILE")"
}
case "${1:-}" in
add)
[[ $# -lt 2 ]] && usage
add_key "$2" "${3:-"no comment"}"
;;
del)
[[ $# -lt 2 ]] && usage
delete_key "$2"
;;
list)
list_keys
;;
*)
usage
;;
esac