view src/main/kotlin/name/blackcap/passman/ReadSubcommand.kt @ 0:a6cfdffcaa94

Initial commit, incomplete but it runs sorta.
author David Barts <n5jrn@me.com>
date Sun, 11 Sep 2022 16:11:37 -0700
parents
children eafa3779aef8
line wrap: on
line source

package name.blackcap.passman

import org.apache.commons.cli.CommandLine
import org.apache.commons.cli.DefaultParser
import org.apache.commons.cli.Options
import org.apache.commons.cli.ParseException

class ReadSubcommand(): Subcommand() {
    private lateinit var commandLine: CommandLine

    override fun run(args: Array<String>) {
        val options = Options().apply {
            addOption("c", "clipboard", false, "Copy username and password into clipboard.")
            addOption("l", "long", false, "Long format listing.")
        }
        try {
            commandLine = DefaultParser().parse(options, args)
        } catch (e: ParseException) {
            die(e.message ?: "syntax error", 2)
        }
        val clipboard = commandLine.hasOption("clipboard")
        val long = commandLine.hasOption("long")
        if (commandLine.args.size != 1) {
            die("expecting site name", 2)
        }
        val nameIn = commandLine.args[0];
        val db = Database.open()
        val id = db.makeKey(nameIn)

        db.connection.prepareStatement("select name, username, password, notes, created, modified, accessed from passwords where id = ?").use {
            it.setLong(1, id)
            val result = it.executeQuery()
            if (!result.next()) {
                die("no record matches $nameIn")
            }
            val entry = Entry(
                name = result.getDecryptedString(1, db.encryption),
                username = result.getDecryptedString(2, db.encryption),
                password = result.getDecrypted(3, db.encryption),
                notes = result.getDecryptedString(4, db.encryption),
                created = result.getDate(5),
                modified = result.getDate(6),
                accessed = result.getDate(7)
            )
            try {
                val redaction = if (clipboard) { "(in clipboard)" } else { null }
                if (long) {
                    entry.printLong(redaction)
                } else {
                    entry.print(redaction)
                }
                if (clipboard) {
                    writeToClipboard(entry.password)
                }
            } finally {
                entry.password.clear()
            }
        }

        db.connection.prepareStatement("update passwords set accessed = ? where id = ?").use {
            it.setLong(1, System.currentTimeMillis())
            it.setLong(2, id)
            it.execute()
        }
    }
}